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