如果我以这种方式使用片段,如何在viewpager中保存片段的状态?

时间:2013-07-12 13:27:51

标签: android android-fragments android-viewpager fragmentstatepageradapter

我想在viewpager中保存片段的状态。我知道我应该这样做:ViewPager and fragments — what's the right way to store fragment's state?。但我这样使用片段:

MyAdapter

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

    }

HostActivity

 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());

}

如何以这种方式保存fragmens状态?我的意思是我需要这种方法:

@Override
protected void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);
    getSupportFragmentManager()
            .putFragment(outState, MessagesFragment.class.getName(), mMessagesFragment);

}

那么我应该在哪里检查if (savedInstanceState != null)的每个片段?我应该如何将碎片放入“州”?

更新 所以我把保存状态代码放到这样的每个片段:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    setUserVisibleHint(true);
    getFragmentManager().putFragment(outState, Tab1Fragment.class.getName(), this);
} 

1 个答案:

答案 0 :(得分:2)

必须将on save状态代码放在您使用的每个片段类中。所以对于你的情况,它在里面:

Tab1Fragment,Tab2Fragment,Tab3Fragment&amp; Tab4Fragment