简体   繁体   中英

save/restore fragment stack on Activity destroyed

In my project, there are Activities and Fragments. And there's an Fragment backstack.

My question is how to save/restore the fragment stack in case of Activity is destroyed by the OS.


@forcewill are you taling about addToBackStack? Yes I did. I'm not talking about popup topmost fragment in case of back pressed. I'm talking about to restore the fragment stack in case of Activity destroyed.


@Derek, I did follow your way to write the following to every fragment and activity to override onStaveInstanceState(...)

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

But it seems like it's still not working.

I have tested on - Galaxy S3 with Android 4.1 - Emulator with Android 5.1 (to turn a debugging option named "Don't keep activity"


@josedlujan, it's not about save single Fragment instance, it's about save the fragments in stack.

Use savedInstanceState

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's state here
    }
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

//Save the fragment's state here



}

Derek Fung is corrrect. As long as the fragment is add to backstack, the fragment backstack will be maintained by the system.

I was stupid, I did something in onResume/onCreate in the activity, which leads to clear up the fragment backstack which has been restored.

Close this

How did I make the stupid mistake


public class MyActivity {
    ....
    onResume() {
        bottomBar.setDefaultIfNotSet();
    }
    ....
}

The method in onResume would clear the Fragment Backstack. In the BottomBar, I didn't save it's state on Activity destroy. So while the Activity is restored, this view doesn't have the knowledge that it's actually restored "not created from scratch"

Thank you Derek and other guys.

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