onSaveInstanceState is not being called in Fragment

后端 未结 2 808
小鲜肉
小鲜肉 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.

    0 讨论(0)
  • 2020-12-21 02:05

    onSaveInstanceState() is only called when the Android system may need to recreate that particular instance of the Fragment. There are many instances of navigating away from the Fragment or even destroying the Fragment where it will not be called. Please consult the documentation for more information, please read the Activity.onSaveInstanceState() documentation as well since that applys here also: http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle) http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

    EDIT: In your case, you must not recreate the fragment every time the user navigates back to the fragment. I recommend considering ViewPager and FragmentPagerAdapter to automatically manage the fragments. Also look at this post: ViewPager and fragments — what's the right way to store fragment's state?

    0 讨论(0)
提交回复
热议问题