I press the navigation drawer, then if I press back button, the app exits rather than returning to the previous activity. If I change the xml file, then this problem doesn\'
@Hiren Patel's answer is the most elegant so far, but you should set:
mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
Or
mDrawerLayout.descendantFocusability = ViewGroup.FOCUS_BEFORE_DESCENDANTS
Just so you don't block the other child views from receiving focus, and thus blocking the soft keyboard for instance.
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.
ListView mDrawerList;
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}else{
super.onBackPressed();
}
}
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();
}
}