Android – Hide navigation drawer when user presses back button

androidnavigationnavigation-drawer

I've followed Google's official developer tutorials here to create a navigation drawer.

At the moment, everything works fine, except for when the user uses the native back button Android provides at the bottom of the screen (along with the home and recent app buttons). If the user navigates back using this native back button, the navigation drawer will still be open. If the user instead navigates back using the ActionBar, the navigation drawer will be closed like I want it to be.

My code is nearly identical to the official tutorials, except for how I handle the user selecting an item on the drawer:

   mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id)
        {
            switch(position)
            {
                case 0:
                {
                    Intent intent = new Intent(MainActivity.this, NextActivity.class);
                    startActivity(intent);
                }
            }
        }
    });

How can I have the navigation drawer be closed when the user navigates back using the native back button? Any advice appreciated. Thanks!

Best Answer

You have to override onBackPressed(). From the docs :

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

So you can have code like this :

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

If is open this method closes it, else falls back to the default behavior.