Reputation: 9967
How can I save a Fragment's state when a user presses the back button, and then restore it the next time I load the fragment? I tried onSaveInstanceState
, but it doesn't get called when I hit back, and the Bundle
passed into onCreate
is null
.
For context, I have a title Activity which starts a new game Activity when the user presses a button (e.g., "New game"). The second (game) activity loads an XML layout in onCreate
which consists of the custom Fragment
. When the user presses the back button, I want to return to the title Activity, but provide a "resume game" button. To do so, I need to save some custom state data for the Fragment.
Upvotes: 1
Views: 1105
Reputation: 3330
By default onSaveInstanceState() call doesn't occur when user press Back
If the user presses the Back button, the current activity is popped from the stack and >destroyed. The previous activity in the stack is resumed. When an activity is destroyed, the >system does not retain the activity's state.
So the way you can do it seems to be: (1) Override activity's onBackPressed() with your own implementation where you (2) Save fragment instance. Take a look at the FragmentManager.saveFragmentInstanceState() - i believe that this is what you need
Upvotes: 1