我已经实施了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):at android.support.v4.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.java:116) E / AndroidRuntime(330):at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:832) E / AndroidRuntime(330):at android.support.v4.view.ViewPager.populate(ViewPager.java:1048) E / AndroidRuntime(330):at android.support.v4.view.ViewPager.populate(ViewPager.java:914) E / AndroidRuntime(330):at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436) E / AndroidRuntime(330):at android.view.View.measure(View.java:17478)E / AndroidRuntime(330): 在 android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364) E / AndroidRuntime(330):at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) E / AndroidRuntime(330):at android.view.View.measure(View.java:17478)E / AndroidRuntime(330): 在 android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364) E / AndroidRuntime(330):at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410) E / AndroidRuntime(330):at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) E / AndroidRuntime(330):at 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;
}
}
和init to pageviewer和set adapter的代码:
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setOffscreenPageLimit(1);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
和设置请求页面的代码:
mViewPager.setCurrentItem(viewPosition, false);