简体   繁体   中英

Save and restore fragment when activity is popped from back stack

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 (eg, "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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM