Retain Fragment state between Activities

Since API Level 13 (HONEYCOMB_MR2, June 2011), you can save and restore the state of a fragment across activities.

  • To save the state, use FragmentManager.saveFragmentInstanceState(), providing a reference to the Fragment whose state you wish to save. The Fragment must be attached at the time you attempt to save its state.

  • To restore the state, use Fragment.setInitialSavedState() with the return value when you instenciate the same Fragment.

    myFragment = new MyFragment();
    myFragment.setInitialSavedState(appState.getMyFragmentState());
    fragmentManager.beginTransaction().add(R.id.container, myFragment).commit();
    

You can persist the SavedState object across activities as you would any other object; one way is to subclass Application as shown above (appState is the instance of our subclass).

Leave a Comment