Search code examples
androidandroid-fragmentsnavigation-drawerandroid-savedstate

How to save state with navigation drawer and fragments


I have an application with a navigation drawer, one activity and many fragments. When I change the device orientation my main activity is recreate and it's my main fragment who appears, not the current fragment. Just like when I launch the app.

How can I restore the current fragment and maybe the data associated with the selected fragment ?

I Have seen this post but it doesn't work : Save fragment state with navigation drawer

Thanks in advance to those who can help me.


Solution

  • I've found that the fragment states are already persisted for you.

    This is what I do: I check if savedInstanceState is null. If it is, I execute the FragmentManager transaction to display the main fragment. If it is not null, it means the fragment state is persisted. I don't do any kind of transaction, and the fragment is recreated for me from the persisted state.