gpt4 book ai didi

android - ViewPager 上的 setCurrentItem()

转载 作者:行者123 更新时间:2023-11-30 00:24:26 30 4
gpt4 key购买 nike

我像这样创建一个自定义 View 寻呼机:

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;
}

并用于主 fragment :

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

setCurrentItem 中,我必须使用哪个数字,直到我没有收到 nullpointer 错误?我希望 NotificationFragment() 类首先在 View 寻呼机上启动

编辑

whit 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

Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item.

问题

mViewPager.setCurrentItem(-1);

不要设置 -1 或 -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);

关于android - ViewPager 上的 setCurrentItem(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45646875/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com