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

93 Views Asked by At

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?

2

There are 2 best solutions below

0
Susheel Karam On BEST ANSWER

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.

3
Arwy Shelke On

just close your drawer if it is open on pressing back button

@override
public void onBackPressed(){
  //DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
  DrawerLayout drawerLayout = result.getDrawerLayout();      
  if(drawerLayout.isDrawerOpen(GravityCompat.START)) {
    //drawer is open
    drawerLayout.closeDrawer(GravityCompat.START); 
    //result.closeDrawer();     
  }
}