Using onSaveInstanceState with fragments in backstack?

前端 未结 4 1484
一向
一向 2020-11-27 15:26

I have fragments I keep in the backstack of FragmentManager. Every fragment state is saved for orientation changes with member variables, like this for example:

<         


        
4条回答
  •  余生分开走
    2020-11-27 15:50

    It is possible that your member variables don't exist anymore because the FragmentManager in your Activity is dying with all of your fragments.

    You need to override the method onSaveInstanceState of your Activity class as well, because you need to save the Activity state before you save the Fragments state.

    As the documentation says:

    There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

    UPDATE

    In your Activity onSaveInstanceState and onRestoreInstanceState, try saving you Fragment references and then restore them with something like this:

    public void onSaveInstanceState(Bundle outState){
        getFragmentManager().putFragment(outState, "myfragment", myfragment);
    }
    public void onRestoreInstanceState(Bundle inState){
        myFragment = getFragmentManager().getFragment(inState, "myfragment");
    }
    

    Tell me then if you had luck! :-)

提交回复
热议问题