ViewPager + Fragments - Fragment未显示

5
我正在尝试使用ViewPager来显示多个片段。目前我只有一个片段,但似乎它从未被实例化。我尝试使用pager.setCurrentItem(0),但适配器中的getItem方法从未被调用。请问在下面的代码中,有人能看出为什么我的片段没有加载吗?
主活动:
public class MainActivity extends SherlockFragmentActivity {

MyPagerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );

    // Create the FragmentPager Adapter and assign it to the viewpager
    adapter = new MyPagerAdapter( getSupportFragmentManager(), this );
    ViewPager pager = ( ViewPager ) findViewById( R.id.pager );
    pager.setAdapter( adapter );
    pager.setCurrentItem( 0 );

    // Setup the tab page indicator
    TabPageIndicator indicator = ( TabPageIndicator ) findViewById( R.id.indicator );
    indicator.setViewPager( pager );
}

class MyPagerAdapter extends FragmentStatePagerAdapter {
    private SparseArray<Fragment> fragmentPageMap;

    public MyPagerAdapter(FragmentManager fm, Activity context) {
        super( fm );
        fragmentPageMap = new SparseArray<Fragment>();
    }

    @Override
    public Fragment getItem(int index) {
        switch ( index ) {
        case 0:
            if ( fragmentPageMap.get( index ) != null ) {
                SherlockListFragment scheduleFragment =  ScheduleListFragment.newInstance();
                fragmentPageMap.put( index, scheduleFragment );
                return scheduleFragment;
            } else {
                return fragmentPageMap.get( index );
            }
        default:
            return null;
        }
    }

    /*@Override
    public void destroyItem(View container, int index, Object object) {
        super.destroyItem( container, index, object );
        fragmentPageMap.remove( index );
    }*/

    @Override
    public CharSequence getPageTitle(int index) {
        return ( ( ViewPagerPage ) fragmentPageMap.get( index ) ).getTitle();
    }

    @Override
    public int getCount() {
        return fragmentPageMap.size();
    }
}

public interface ViewPagerPage {
    String getTitle();
}

主活动布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<com.viewpagerindicator.TabPageIndicator
    android:id="@+id/indicator"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

</LinearLayout>

日程列表碎片

public class ScheduleListFragment extends SherlockListFragment implements ViewPagerPage {

private ScheduleAdapter adapter;
private final String TITLE = "Schedule";

public static ScheduleListFragment newInstance() {
    ScheduleListFragment newFrag = new ScheduleListFragment();
    Bundle args = new Bundle();
    newFrag.setArguments( args );
    return newFrag;
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate( R.layout.fragment_schedule_list, null );
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate( R.menu.fragment_schedule_list, menu );
}

// Container Activity must implement this interface
public interface OnAddItemClickedListener {
    public void onAddItemClicked();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch ( item.getItemId() ) {
    case R.id.add_item:
        Intent myIntent = new Intent( getActivity(), AddScheduleItemActivity.class );
        startActivityForResult( myIntent, 1 );

        return true;
    default:
        return super.onOptionsItemSelected( item );
    }
}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated( savedInstanceState );
    setHasOptionsMenu( true );

    adapter = new ScheduleAdapter( getActivity() );

    setListAdapter( adapter );
}

private class SampleItem {
    public String tag;
    public int iconRes;

    public SampleItem(String tag, int iconRes) {
        this.tag = tag;
        this.iconRes = iconRes;
    }
}

public class ScheduleAdapter extends ArrayAdapter<SampleItem> {

    public ScheduleAdapter(Context context) {
        super( context, 0 );
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        if ( convertView == null ) {
            convertView = LayoutInflater.from( getContext() ).inflate( R.layout.results_list_row, null );
        }
        ImageView icon = ( ImageView ) convertView.findViewById( R.id.row_icon );
        icon.setImageResource( getItem( position ).iconRes );
        TextView title = ( TextView ) convertView.findViewById( R.id.row_title );
        title.setText( getItem( position ).tag );

        return convertView;
    }

}

@Override
public String getTitle() {
    return TITLE;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ( resultCode == android.app.Activity.RESULT_OK ) {
        String name = ( String ) data.getExtras().get( "TEXT" );
        Toast.makeText( getActivity(), name, Toast.LENGTH_LONG ).show();
    }
}

片段布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

谢谢,Nathan

目前的解决方案:

更改适配器构造函数以初始化第一个片段并将其添加到内部地图中。是否有人认为这样做有问题或者有任何可以改进以上代码的方法?谢谢!

public MyPagerAdapter(FragmentManager fm, Activity context) {
        super( fm );
        fragmentPageMap = new SparseArray<Fragment>();
        SherlockListFragment scheduleFragment = ScheduleListFragment.newInstance();
        fragmentPageMap.put( 0, scheduleFragment );
    }
1个回答

4

getCount()MyPagerAdapter中返回0,因此不会创建任何Fragment,如果您想要实例化N个Fragment,则应该返回N

fragmentPageMap是在构造函数中创建的,在调用getCount()时为空,并且getCount()getItem(index)之前被调用,这就是为什么getCount()返回0的原因。

在这种情况下,您不需要switch,因为每次都实例化相同的Fragment。但是,如果您要实例化不同的Fragments,则需要使用它。

@Override
public Fragment getItem(int index) {
  switch (index) {
    case 0:
      return new Fragment1();
    case 1:
      return new Fragment2();
  }
  return null;
}

为什么你认为getCount()返回0?请详细阐述以获得更好的答案。 - Eric J.
因为fragmentPageMap是在构造函数中创建的,并且在调用getItem(index)之前,getCount()被调用,此时fragmentPageMap为空。您可以在调试器中检查这一点。 - rubenlop88
谢谢!你说的返回0是对的。然而,我认为这个值不应该是硬编码的,我想要能够动态地添加/删除片段。switch语句存在是因为很快会添加更多的片段。 - Nath5
谢谢,我已经更新了答案。动态添加和移除片段可能会是另一个问题的内容 :) - rubenlop88
感谢您的回复!目前一切都运行良好。当我开始添加动态片段时,我会看看它是如何运作的,如果我无法弄清楚,我会发布另一个问题。 - Nath5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接