RominaV RominaV - 1 month ago 17
Android Question

DrawerLayout loses state on orientation change

I'm toggling a DrawerLayout's state from a button's onClick, and disabling its swipe.
That works OK, but when the Activity changes its orientation, the Drawer doesn't retain its state; if it was opened, it will get closed. It even happens adding

android:configChanges="keyboardHidden|orientation"
.

Code in my Activity:

private DrawerLayout drawer;
private int drawerLayoutGravity = Gravity.RIGHT;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
disableDrawer();

View btnOpenDrawer = findViewById(R.id.btn_open_drawer);
btnOpenDrawer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggleDrawerState();
}
});
}

private void toggleDrawerState() {
if (drawer.isDrawerOpen(drawerLayoutGravity)) {
drawer.closeDrawer(drawerLayoutGravity);
} else {
drawer.openDrawer(drawerLayoutGravity);
}
}

/**
* doesn't let the user swipe to open the drawer
*/
private void disableDrawer() {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}


A possible solution is that I re open the DrawerLayout on the Activity's
onConfigurationChanged
, but I need to avoid showing the DrawerLayout re opening when the configuration changes.

Answer

You're setting a closed lock mode on the drawer to disable swiping. Even though you've disabled Activity re-creation, the orientation change will trigger a layout event on your Views, and the DrawerLayout will set the drawer state according to the lock mode when laying itself out.

You need to update the lock mode whenever you programmatically open/close the drawer.

private void toggleDrawerState() {
    if (drawer.isDrawerOpen(drawerLayoutGravity)) {
        drawer.closeDrawer(drawerLayoutGravity);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    } else {
        drawer.openDrawer(drawerLayoutGravity);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
    }
}
Comments