How to stay on same fragment during orientation change?

1.3k Views Asked by At

I've been following this tutorial to work on navigation drawers that have the draw open on first launch. That portion works wonderfully. The problem I am now having is that upon orientation change it goes back to the first fragment instead of staying on the current one. I've tried adding in the following code to help with this but it's not helping.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
    getSupportActionBar().setTitle(mTitle);
}

This works great for the tutorial that Google has but I can't get the drawer to open on first run and be able to close the drawer on item select (that's a different issue).

I've also tried adding adroid:configChanges="orientation|screenSize" to the manifest with no help.

Can anyone give me some advice on how to stop things from changing when switching to landscape? I've been working on this for a couple of weeks now. :/

1

There are 1 best solutions below

0
On

The created Fragments will be re-attached to the activity after the orientation changes, so check if savedInstanceState is null (First time running), then create the Fragments and attach them.

Upon Configuration change (Orientation changing), your onCreate will get called again, what you need to worry about now is show the last selected Fragment before the orientation changed, so what you can do is Override onSaveInstanceState to store a reference to the selected Fragment (index value for example) in the bundle, then get that value in your onCreate's bundle and use FragmentTransaction to show the appropriate Fragment.

Not sure if that's the best way to handle it but that's the way I went with since I found nothing else.

As for closing the drawer, you can check if the drawer is open with drawer.isDrawerOpen and close it with drawer.closeDrawer, that's not working for you? Make sure to add those inside your Click Listener.

Hope that's of any help to you, good luck.