0

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.

Community
  • 1
  • 1
Jhiertz
  • 90
  • 6
  • did you tried adding configchanges to the manifest – Sarthak Mittal Mar 13 '16 at 21:14
  • I thought of something that can be considered a hack; whenever you enter a new fragment, save its' position into the SharedPreferences and then onConfigurationChange read the position from SharedPrefs and instantiate the right fragment. – Vucko Mar 13 '16 at 22:35

2 Answers2

0

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.

kris larson
  • 30,387
  • 5
  • 62
  • 74
  • Thanks for your help, in my onCreate I executed the `FragmentManager` to display one or another Fragment according to `SharedPreferences`. So I just added the condition on `savedInstanceState == null`. – Jhiertz Mar 14 '16 at 19:58
0
if (savedInstanceState == null){
    //Launch HomeFragment onStart...
    Fragment fragment = new HomeFragment();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.frame, fragment).commit();
}

I added this to onCreate in my Main Activity

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135