Drawer Layout not closing on back pressed (depending on support-v4 lib)
I have the exactly same problem after upgrading the support library to 20.0.0.
Add below one line code can fix my problem. (onCreate in my activitiy)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawerLayout = (DrawerLayout) this.findViewById(R.id.drawer_layout);
mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); /* add this line */
....
}
Here is a quick fix to your problem. Just override the onBackPressed()
method in your Activity / Fragment :
@Override
public void onBackPressed()
{
if (mDrawerLayout.isDrawerOpen(Gravity.START))
mDrawerLayout.closeDrawer(Gravity.START);
else
super.onBackPressed();
}
Use Gravity.START
for the left drawer, Gravity.END
for the right one
The solution with mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
is not recommend because you can't gain focus if you have a TextEdit on the activity. Better use the onBackPressed()
solution as it mentioned before.
@Override
public void onBackPressed()
{
if (mDrawerLayout.isOpen())
mDrawerLayout.close();
else
super.onBackPressed();
}
In setUpNavDrawer
mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
Also
@Override
public void onBackPressed()
{
if (mDrawerLayout.isOpen())
mDrawerLayout.close();
else
super.onBackPressed();
}