ViewPager and fragments — what's the right way to store fragment's state?

后端 未结 11 1351
遇见更好的自我
遇见更好的自我 2020-11-22 02:21

Fragments seem to be very nice for separation of UI logic into some modules. But along with ViewPager its lifecycle is still misty to me. So Guru thoughts are b

11条回答
  •  梦谈多话
    2020-11-22 02:41

    My solution is very rude but works: being my fragments dynamically created from retained data, I simply remove all fragment from the PageAdapter before calling super.onSaveInstanceState() and then recreate them on activity creation:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("viewpagerpos", mViewPager.getCurrentItem() );
        mSectionsPagerAdapter.removeAllfragments();
        super.onSaveInstanceState(outState);
    }
    

    You can't remove them in onDestroy(), otherwise you get this exception:

    java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

    Here the code in the page adapter:

    public void removeAllfragments()
    {
        if ( mFragmentList != null ) {
            for ( Fragment fragment : mFragmentList ) {
                mFm.beginTransaction().remove(fragment).commit();
            }
            mFragmentList.clear();
            notifyDataSetChanged();
        }
    }
    

    I only save the current page and restore it in onCreate(), after the fragments have been created.

    if (savedInstanceState != null)
        mViewPager.setCurrentItem( savedInstanceState.getInt("viewpagerpos", 0 ) );  
    

提交回复
热议问题