Search code examples
androidandroid-fragmentsnavigation-drawerscreen-rotation

Fragment changes on rotation with navigation drawer


CURRENT SCENARIO

In my app I am having navigation drawer with fragments. Everything works fine in portrait mode.

PROBLEM

Suppose when in portrait mode I select second item from navigation drawer. It loads perfectly but when I rotate my phone to landscape mode, first fragment from the navigation menu gets loaded instead of second.

I know I have to save instance for fragment but I don't know how to do it and should I do it in main activity or in fragment itself


Solution

  • You should do that in your Fragment.

    Just follow these links:

    Android - save/restore fragment state

    Or perhaps:

    Once for all, how to correctly save instance state of Fragments in back stack?

    Also, let's mention about onRestoreInstanceState, Fragment's doesn't have that method.So, you should use onActivityCreated which receives a bundle with the saved instance state (or null).

    Take a look at the docs:

    http://developer.android.com/reference/android/app/Fragment.html#onActivityCreated(android.os.Bundle)