Retain Fragment state between Activities

Axel M. Garcia picture Axel M. Garcia · May 17, 2011 · Viewed 14.1k times · Source

Its possible to retain a Fragment between Activities?

Lets say I have Activity A with Fragment F_Left placed at the left and Fragment F_Right placed at the right. If I want to launch a new Activity and keep Fragment F_Left... how can I do it?

Can I retain Fragment F_Left state between activities?

Note that I want to launch a new Activity because Fragment F_Left is my app menu and Fragment F_Right changes completely the context of the user operations... and my app have many of operations, so it makes sense to have an Activity per operation.

I know its possible to retain Fragment within an Activity, but as Fragment life cycle is closely tied to the container Activity I don't know if this is possible keep Fragment state between Activities.

Answer

quietmint picture quietmint · Sep 17, 2012

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