Retain Fragment state between Activities

前端 未结 4 1881
孤街浪徒
孤街浪徒 2020-12-03 01:51

Its possible to retain a Fragment between Activities?

Lets say I have Activity A with Fragment F_Left placed at the left and F

4条回答
  •  囚心锁ツ
    2020-12-03 02:35

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

提交回复
热议问题