androidnavigation-drawerdrawermaterialdrawer

Android - MaterialDrawer when bakc press go back activity instead closing drawer


I am using MaterialDrawer from: https://github.com/mikepenz/MaterialDrawer

and when the user presses the back button, the app goes one activity backwards, instead of just closing the drawer.

is it a bug or there is a way to fix it?


Solution

  • This is expected behavior. If you want to close Drawer on Back press, you have to override the onBackPressed() function.

    First get a reference to your DrawerLayout :

    DrawerLayout myDrawer = (DrawerLayout) findViewById(R.id.my_drawer);
    

    Then override the onBackPressed() function to close drawer when it is open instead of closing activity:

    @Override
    public void onBackPressed() {
        if (myDrawer.isDrawerOpen(GravityCompat.START)) {
            myDrawer.closeDrawer(GravityCompat.START);
        } 
        else {
            super.onBackPressed();
        }
    }
    

    Hope it helps.