onSaveInstanceState is not being called in Fragment

后端 未结 2 810
小鲜肉
小鲜肉 2020-12-21 01:32

I know that people have asked this question, but I followed all the answers and I still have the same problem. I have two scripts One is the fragment manager (IngredientsAct

2条回答
  •  时光取名叫无心
    2020-12-21 02:03

    I had a similar problem where I was trying to get a Fragment to save its state but onSaveInstanceState() wasn't being called on FragmentTransaction.replace(). I was trying to find a solution for this and thought, if the Fragment itself can't save its own state then can't whatever is doing the replacing save it. So I did something like this:

    In the Fragment have a method called getState() or whatever you want:

    public Bundle getState()
    {
        // save whatever you would have in onSaveInstanceState() and return a bundle with the saved data
    }
    

    Then in the hosting object, save that bundle to its instance variables before replacing the Fragment and set the argument to that saved bundle when switching back.

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    // assume Fragment a exists and you're trying to save the state and "state" is an instance variable
    state = a.getState();
    ft.replace(android.R.id.content, b);
    

    Then when swapping back to Fragment a you would pass the bundle as an argument.

    a.setArguments(state);
    ft.replace(android.R.id.content, a);
    

    I didn't look into your code too deeply but it sounds similar to the problem I had from your description.

提交回复
热议问题