我想将片段的状态保存在 viewpager 中。我知道我应该这样做:ViewPager 和 Fragments — 存储 Fragment 状态的正确方法是什么?. 但我以这种方式使用片段:
我的适配器
class MyPagerAdapter extends FragmentStatePagerAdapter {
public List<String> fragmentsA; //plus
public MyPagerAdapter(FragmentManager fm) {
super(fm);
fragmentsA = fragments;//plus
}
@Override
public Fragment getItem(int position) {
//return MyFragment.newInstance();
return Fragment.instantiate(context, fragmentsA.get(position));
}
@Override
public CharSequence getPageTitle(int position) {
//return CONTENT[position % CONTENT.length].toUpperCase();
return mEntries.get(position % CONTENT.length).toUpperCase();
}
@Override
public int getCount() {
// return CONTENT.length;
return mEntries.size();
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
主机活动
public static List<String> fragments = new Vector<String>();
@Override
public void onCreate( Bundle savedInstanceState )
{
pager = (ViewPager)findViewById( R.id.viewpager );
adapter = new MyPagerAdapter(getSupportFragmentManager());
indicator = (TabPageIndicator)findViewById( R.id.indicator );
pager.setAdapter( adapter );
indicator.setViewPager( pager );
pager.setCurrentItem(INITIAL_PAGE);
//mEntries.add...
fragments.clear();
fragments.add( Tab1Fragment.class.getName());
fragments.add( Tab2Fragment.class.getName());
fragments.add( Tab3Fragment.class.getName());
fragments.add( Tab4Fragment.class.getName());
}
我怎样才能以这种方式保存碎片状态?我的意思是我需要这个方法:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager()
.putFragment(outState, MessagesFragment.class.getName(), mMessagesFragment);
}
那么我应该在哪里检查每个片段if (savedInstanceState != null)
呢?我应该如何将碎片放入“outstate”?
更新 所以我将保存状态代码放在每个片段中,如下所示:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
getFragmentManager().putFragment(outState, Tab1Fragment.class.getName(), this);
}