我已经实现ViewPager和片段(比如A,B,C,d,E),其为儿童。
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter); // FragmentStatePagerAdapter
然后后我称为mViewPager.setCurrentItem(3, false);
这是给NullPointerException异常。 以下日志:
显示java.lang.NullPointerException E / AndroidRuntime(330):在android.support.v4.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.java:116)E / AndroidRuntime(330):在android.support.v4.view.ViewPager.addNewItem (ViewPager.java:832)E / AndroidRuntime(330):在android.support.v4.view.ViewPager.populate(ViewPager.java:1048)E / AndroidRuntime(330):在android.support.v4.view.ViewPager .populate(ViewPager.java:914)E / AndroidRuntime(330):在android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)E / AndroidRuntime(330):在android.view.View.measure (View.java:17478)E / AndroidRuntime(330):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)E / AndroidRuntime(330):在android.widget.FrameLayout.onMeasure(FrameLayout.java:310 )E / AndroidRuntime(330):在android.view.View.measure(View.java:17478)E / AndroidRuntime(330):在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)E / AndroidRuntime(330 ):在android.widget.LinearLayout.measu reChildBeforeLayout(LinearLayout.java:1410)E / AndroidRuntime(330):在android.widget.LinearLayout.measureVertical(LinearLayout.java:695)E / AndroidRuntime(330):在android.widget.LinearLayout.onMeasure(LinearLayout.java: 588)
我猜这里,可能是PageViewer没有加载我要求的页面,但我在这里等也是之前加载,但它是同样的结果。
没有任何一个有相同的任何建议。
编辑: 适配器类
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (id) {
case 0:
fragment = new TestFragment1();
Bundle args = new Bundle();
args.putInt("position", position + 1);
fragment.setArguments(args);
break;
case 1:
fragment = new TestFragment2();
args = new Bundle();
args.putInt("position", position + 1);
fragment.setArguments(args);
break;
case 3:
fragment = new TestFragment4();
args = new Bundle();
args.putInt("position", position + 1);
fragment.setArguments(args);
break;
case 4:
fragment = new TestFragment5();
args = new Bundle();
args.putInt("position", position + 1);
fragment.setArguments(args);
break;
}
return fragment;
}
@Override
public int getCount() {
return total_child_count;
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
和代码初始化pageviewer和一套适配器:
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setOffscreenPageLimit(1);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
和代码设置申请页面:
mViewPager.setCurrentItem(viewPosition, false);