How to close Drawer layout on BackPress in Android?

ListView mDrawerList;

@Override
public void onBackPressed() {
// TODO Auto-generated method stub

if(mDrawerLayout.isDrawerOpen(mDrawerList)){
    mDrawerLayout.closeDrawer(mDrawerList);
}else{
    super.onBackPressed();
}
}

I have done this way:

private DrawerLayout mDrawerLayout;

onCreate():

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);  
mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

Hope this will help you.


This will close the drawer when it's open and back is pressed rather than taking you back to the previous activity (or exiting).

DrawerLayout drawer...

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

    if(drawer.isDrawerOpen(Gravity.LEFT)){
        drawer.closeDrawer(Gravity.LEFT);
    }else{
        super.onBackPressed();
    }
}

Tags:

Android