我在ViewPager为3个片段的Activity中有以下功能
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, NewsListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, MinistriesListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, NewsListFragment.class.getName()));
mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments, mTabsName);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mViewPager.setAdapter(mPagerAdapter);
Fragment newsfragment = ((PagerAdapter)mViewPager.getAdapter()).getFragment(0);
// Why is my newsfragment = null??
}
我正试图获取片段,设置listAdapter。但是,即使添加到适配器后片段仍然为空。我尝试在onStart和onResume中获取它,它仍然没有成功。
显然它仍然为空的原因是因为下面的函数在pagerAdapter中仍未被调用
public Object instantiateItem(ViewGroup container, int position)
有人可以说清楚,我应该何时从PagerAdapter调用getFragment(xx)?如果我稍后调用(例如从ViewPager选项卡滑动到选项卡),则片段已准备就绪。谢谢!