Search code examples
androidandroid-layoutdrawerlayoutscreen-rotation

Incoherent DrawerLayout behavior after rotation


I have an activity with a DrawerLayout and a ActionBarDrawerToggle to handle a side menu.

Now, I needed this activity to rotate only on tablets but not on phone, so I added android:configChanges="orientation|..." to my manifest for that activity, and reimplemented onConfigurationChanged. On phones, nothing is done and portrait is forced, while on tablets, the new orientation is set to SCREEN_ORIENTATION_SENSOR to let the device decide and I reload the layout with setContentView().

Since I've done that, my side menu won't open past the first rotation. I discovered that onOptionsItemSelected is still called:

public boolean onOptionsItemSelected(MenuItem item)
{
    if (item.getItemId() == android.R.id.home) {
        if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        }
        else {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
    }
    return true;
}

but the test that check if the drawer is visible always returns true.

Any idea on what could cause that? Did I forget to recreate or update something after the rotation in onConfigurationChanged?

Note: I also found out that if I don't recreate the layout (with setContentView()) the drawer works fine (but then I obviously lose the landscape layout and get the portrait layout somehow scaled)


Solution

  • So, I somehow found a solution to this, by reconnecting the DrawerLayout to the ActionBarDrawerToggle each time the device rotates, after recreating the layout:

        setContentView(R.id.my_layout_id);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    

    in the onConfigurationChanged method.

    The only downside to that is that the drawer won't keep its state between the two orientation (if it was opened, it'll be recreated and thus end up closed in the new orientation).