在我的活动中,为了防止在配置更改中重新生成片段:
if(getSupportFragmentManager().findFragmentByTag(MAIN_TAB_FRAGMENT) == null) { getSupportFragmentManager().beginTransaction().replace(R.ID.container,new MainTabFragment(),MAIN_TAB_FRAGMENT).commit();}
片段代码B:
public class MainTabFragment extends Fragment { private PagerSlIDingTabStrip mSlIDingTabLayout; private LfPagerAdapter adapter; private VIEwPager mVIEwPager; @OverrIDe public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Nullable @OverrIDe public VIEw onCreateVIEw(LayoutInflater inflater,VIEwGroup container,Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_tab,container,false); } @OverrIDe public voID onVIEwCreated(VIEw vIEw,Bundle savedInstanceState) { this.adapter = new LfPagerAdapter(getChildFragmentManager()); this.mVIEwPager = (VIEwPager) vIEw.findVIEwByID(R.ID.vIEwpager); this.mVIEwPager.setAdapter(adapter); this.mSlIDingTabLayout = (PagerSlIDingTabStrip) vIEw.findVIEwByID(R.ID.slIDing_tabs); this.mSlIDingTabLayout.setVIEwPager(this.mVIEwPager); }}
适配器代码:
public class LfPagerAdapter extends FragmentPagerAdapter { private static final int NUM_ITEMS = 3; private FragmentManager fragmentManager; public LfPagerAdapter(FragmentManager fm) { super(fm); this.fragmentManager = fm; } @OverrIDe public int getCount() { return NUM_ITEMS; } @OverrIDe public Fragment getItem(int @R_404_4612@) { Log.d("TEST","TEST"); switch (@R_404_4612@) { case 1: return FragmentC.newInstance(); case 2: return FragmentD.newInstance(); default: return FragmentE.newInstance(); } }}
我的问题是,我无法保留视图寻呼机的状态,它的小孩片段的方向更改.
显然,这是每个轮回的要求:
this.adapter = new LfPagerAdapter(getChildFragmentManager());
这将导致整个寻呼机被重新创建,对吧?结果是
getItem(int @R_404_4612@)
将会在每个轮播中被调用,片段将从头创建并丢失其状态:
return FragmentC.newInstance();
我试着解决这个问题:
if(this.adapter == null) this.adapter = new LfPagerAdapter(getChildFragmentManager());
在onVIEwCreated中,但是结果是旋转了被移除的寻呼机内的碎片.
任何想法如何正确保留传呼机内的状态?
解决方法 您需要做两件事来解决问题:1)您应该使用onCreate方法代替onVIEwCreated来实例化LfPagerAdapter;
即:
public class MainTabFragment extends Fragment { private PagerSlIDingTabStrip mSlIDingTabLayout; private LfPagerAdapter adapter; private VIEwPager mVIEwPager; @OverrIDe public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); this.adapter = new LfPagerAdapter(getChildFragmentManager()); } @Nullable @OverrIDe public VIEw onCreateVIEw(LayoutInflater inflater,Bundle savedInstanceState) { this.mVIEwPager = (VIEwPager) vIEw.findVIEwByID(R.ID.vIEwpager); this.mVIEwPager.setAdapter(adapter); this.mSlIDingTabLayout = (PagerSlIDingTabStrip) vIEw.findVIEwByID(R.ID.slIDing_tabs); this.mSlIDingTabLayout.setVIEwPager(this.mVIEwPager); }}
2)您将需要扩展FragmentStatePagerAdapter而不是FragmentPagerAdapter
总结以上是内存溢出为你收集整理的android – ViewPager里面的片段,怎么保留状态?全部内容,希望文章能够帮你解决android – ViewPager里面的片段,怎么保留状态?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)