我创建一个这样的自定义视图寻呼机:

public class TaskPagerAdapter extends FragmentStatePagerAdapter {

public TaskPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;

    switch (position) {
        case 0:
            fragment = new NotificationFragment();
            break;
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;

    }
    return fragment;
}

@Override
public int getCount() {
    return 5;
}


@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}


}

并用于主要片段:

        mPagerAdapter = new TaskPagerAdapter(getFragmentManager());
    mViewPager.setAdapter(mPagerAdapter);
    mViewPager.setCurrentItem(-2);


在setCurrentItem中,我必须使用哪个编号,直到我没有收到nullpoiner错误为止?我希望NotificationFragment()类首先在视图寻呼机上启动

编辑

mViewPager.setCurrentItem(-1);我受到打击错误:

 Process: safarayaneh.com.anotify.debug, PID: 21484
                                                                           java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference
                                                                               at android.support.v4.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.java:120)
                                                                               at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1034)
                                                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1248)
                                                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                               at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                               at android.view.View.measure(View.java:18788)
                                                                               at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1028)...

最佳答案

阅读setCurrentItem


  设置当前选择的页面。如果ViewPager已经
  通过其当前适配器的第一个布局,将有一个
  当前项目和指定项目之间的平滑动画过渡
  项目。


问题

mViewPager.setCurrentItem(-1);


不要设置-1 or -2。索引从0开始。

编辑

switch (position) {
    case 0:
        fragment = new NotificationFragment();
        break;
    case 1:
        break;
    case 2:
        break;
    case 3:
        break;
    case 4:
        break;

}
return fragment;


为什么1,2,3,4空白。你应该尝试

 switch (position) {
    case 0:
        fragment = new NotificationFragment();
        break;

}
return fragment;


mViewPager.setCurrentItem(0);

10-06 15:01