Hide navigation drawer when user presses back button
Asked Answered
H

12

28

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!

Hamfurd answered 9/11, 2014 at 21:52 Comment(0)
G
71

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.

Gudrun answered 9/11, 2014 at 22:10 Comment(2)
Use isDrawerVisibleinstead of isDrawerOpen if you want to close the drawer while opening when pressing the back button instead of closing the app in this moment.Cherry
Probably a lot easier to close the drawer upon opening the drawer items (and it saves you the animation): https://mcmap.net/q/486324/-hide-navigation-drawer-when-user-presses-back-buttonEucharis
W
10

You need to override onBackPressed() in your activity and check for the condition where the navigation drawer is open. If it is open, then close it, else do a normal back pressed method. Here is some code mixed with some pseudocode to help you:

@Override
public void onBackPressed(){
  if(drawer.isDrawerOpen()){ //replace this with actual function which returns if the drawer is open
   drawer.close();     // replace this with actual function which closes drawer
  }
  else{
   super.onBackPressed();
  }
}

To replace the pseudocode look in the documentation for the drawer. I know both those methods exist.

Warlike answered 9/11, 2014 at 22:12 Comment(0)
C
5

Here is an alternative solution to your problem.

@Override    
public void onBackPressed(){    
    if(drawerLayout.isDrawerOpen(navigationView)){    
        drawerLayout.closeDrawer(navigationView);    
    }else {    
        finish();    
    }    
}    
Colier answered 3/10, 2016 at 6:11 Comment(0)
P
4

UPDATE:

As of support library 24.0.0 this is possible without any workarounds. Two new openDrawer and closeDrawer methods have been added to DrawerLayout that allow the drawer to be opened or closed with no animation.

You can now use openDrawer(drawerView, false) and closeDrawer(drawerView, false) to open and close the drawer with no delay.


If you call startActivity() without calling closeDrawer(), the drawer will be left open in that instance of the activity when you navigate back to it using the back button. Calling closeDrawer() when you call startActivity() has several issues, ranging from choppy animation to a long perceptual delay, depending on which workaround you use. So I agree the best approach is to just call startActivity() and then close the drawer upon return.

To make this work nicely, you need a way to close the drawer without a close animation when navigating back to the activity with the back button. (A relatively wasteful workaround would be to just force the activity to recreate() when navigating back, but it's possible to solve this without doing that.)

You also need to make sure you only close the drawer if you're returning after navigating, and not after an orientation change, but that's easy.


Details

(You can skip past this explanation if you just want to see the code.)

Although calling closeDrawer() from onCreate() will make the drawer start out closed without any animation, the same is not true from onResume(). Calling closeDrawer() from onResume() will close the drawer with an animation that is momentarily visible to the user. DrawerLayout doesn't provide any method to close the drawer without that animation, but it's possible to extend it in order to add one.

Closing the drawer actually just slides it off the screen, so you can effectively skip the animation by moving the drawer directly to its "closed" position. The translation direction will vary according to the gravity (whether it's a left or right drawer), and the exact position depends on the size of the drawer once it's laid out with all its children.

However, simply moving it isn't quite enough, as DrawerLayout keeps some internal state in extended LayoutParams that it uses to know whether the drawer is open. If you just move the drawer off screen, it won't know that it's closed, and that will cause other problems. (For example, the drawer will reappear on the next orientation change.)

Since you're compiling the support library into your app, you can create a class in the android.support.v4.widget package to gain access to its default (package-private) parts, or extend DrawerLayout without copying over any of the other classes it needs. This will also reduce the burden of updating your code with future changes to the support library. (It's always best to insulate your code from implementation details as much as possible.) You can use moveDrawerToOffset() to move the drawer, and set the LayoutParams so it will know that the drawer is closed.


Code

This is the code that'll skip the animation:

        // move drawer directly to the closed position
        moveDrawerToOffset(drawerView, 0.f); 
        
        // set internal state so DrawerLayout knows it's closed
        final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
        lp.onScreen = 0.f;
        lp.knownOpen = false;

        invalidate();

Note: if you just call moveDrawerToOffset() without changing the LayoutParams, the drawer will move back to its open position on the next orientation change.


Option 1 (use existing DrawerLayout)

This approach adds a utility class to the support.v4 package to gain access to the package-private parts we need inside DrawerLayout.

Place this class into /src/android/support/v4/widget/:

package android.support.v4.widget;

import android.support.annotation.IntDef;
import android.support.v4.view.GravityCompat;
import android.view.Gravity;
import android.view.View;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class Support4Widget {

    /** @hide */
    @IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END})
    @Retention(RetentionPolicy.SOURCE)
    private @interface EdgeGravity {}

    public static void setDrawerClosed(DrawerLayout drawerLayout, @EdgeGravity int gravity) {
        final View drawerView = drawerLayout.findDrawerWithGravity(gravity);
        if (drawerView == null) {
            throw new IllegalArgumentException("No drawer view found with gravity " +
                    DrawerLayout.gravityToString(gravity));
        }

        // move drawer directly to the closed position
        drawerLayout.moveDrawerToOffset(drawerView, 0.f); 
        
        // set internal state so DrawerLayout knows it's closed
        final DrawerLayout.LayoutParams lp = (DrawerLayout.LayoutParams) drawerView.getLayoutParams();
        lp.onScreen = 0.f;
        lp.knownOpen = false;

        drawerLayout.invalidate();
    }
}

Set a boolean in your activity when you navigate away, indicating the drawer should be closed:

public static final String CLOSE_NAV_DRAWER = "CLOSE_NAV_DRAWER";
private boolean mCloseNavDrawer;

@Override
public void onCreate(Bundle savedInstanceState) {
    // ...
    if (savedInstanceState != null) {
        mCloseNavDrawer = savedInstanceState.getBoolean(CLOSE_NAV_DRAWER);
    }
}

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {

    // ...

    startActivity(intent);
    mCloseNavDrawer = true;
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(CLOSE_NAV_DRAWER, mCloseNavDrawer);
    super.onSaveInstanceState(savedInstanceState);
}   

...and use the setDrawerClosed() method to shut the drawer in onResume() with no animation:

@Overrid6e
protected void onResume() {
    super.onResume();

    if(mCloseNavDrawer && mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        Support4Widget.setDrawerClosed(mDrawerLayout, GravityCompat.START);
        mCloseNavDrawer = false;
    }
}

Option 2 (extend from DrawerLayout)

This approach extends DrawerLayout to add a setDrawerClosed() method.

Place this class into /src/android/support/v4/widget/:

package android.support.v4.widget;

import android.content.Context;
import android.support.annotation.IntDef;
import android.support.v4.view.GravityCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class CustomDrawerLayout extends DrawerLayout {

    /** @hide */
    @IntDef({Gravity.LEFT, Gravity.RIGHT, GravityCompat.START, GravityCompat.END})
    @Retention(RetentionPolicy.SOURCE)
    private @interface EdgeGravity {}
    
    public CustomDrawerLayout(Context context) {
        super(context);
    }

    public CustomDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    
    public void setDrawerClosed(View drawerView) {
        if (!isDrawerView(drawerView)) {
            throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer");
        }
        
        // move drawer directly to the closed position
        moveDrawerToOffset(drawerView, 0.f); 
        
        // set internal state so DrawerLayout knows it's closed
        final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
        lp.onScreen = 0.f;
        lp.knownOpen = false;
        
        invalidate();
    }

    public void setDrawerClosed(@EdgeGravity int gravity) {
        final View drawerView = findDrawerWithGravity(gravity);
        if (drawerView == null) {
            throw new IllegalArgumentException("No drawer view found with gravity " +
                    gravityToString(gravity));
        }

        // move drawer directly to the closed position
        moveDrawerToOffset(drawerView, 0.f); 
        
        // set internal state so DrawerLayout knows it's closed
        final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
        lp.onScreen = 0.f;
        lp.knownOpen = false;

        invalidate();
    }
}

Use CustomDrawerLayout instead of DrawerLayout in your activity layouts:

<android.support.v4.widget.CustomDrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    >

...and set a boolean in your activity when you navigate away, indicating the drawer should be closed:

public static final String CLOSE_NAV_DRAWER = "CLOSE_NAV_DRAWER";
private boolean mCloseNavDrawer;

@Override
public void onCreate(Bundle savedInstanceState) {
    // ...
    if (savedInstanceState != null) {
        mCloseNavDrawer = savedInstanceState.getBoolean(CLOSE_NAV_DRAWER);
    }
}

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {

    // ...

    startActivity(intent);
    mCloseNavDrawer = true;
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(CLOSE_NAV_DRAWER, mCloseNavDrawer);
    super.onSaveInstanceState(savedInstanceState);
}   

...and use the setDrawerClosed() method to shut the drawer in onResume() with no animation:

@Overrid6e
protected void onResume() {
    super.onResume();

    if(mCloseNavDrawer && mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.setDrawerClosed(GravityCompat.START);
        mCloseNavDrawer = false;
    }
}
Preprandial answered 15/7, 2015 at 1:40 Comment(0)
H
3

Using an implementation of the answer provided by @James Cross worked, but the animation to close the drawer was undesirable and unfixable without much hassle, example.

@Override
public void onResume()
{
    super.onResume();
    mDrawerLayout.closeDrawers();
}

A work-around is to restart the activity when the device back button is pressed. It does not seem ideal to me, but it works. Overriding onBackPressed(), as suggested by @mt0s and @Qazi Ahmed and passing an extra to determine the calling activity:

    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);
                    //pass int extra to determine calling activity
                    intent.putExtra(EXTRA_CALLING_ACTIVITY, CallingActivityInterface.MAIN_ACTIVITY);
                    startActivity(intent);
                }
            }
        }
    });

In NextActivity.class, check for the calling activity:

@Override
public void onBackPressed()
{
    int callingActivity = getIntent().getIntExtra(EXTRA_CALLING_ACTIVITY, CallingActivityInterface.MAIN_ACTIVITY);
    switch(callingActivity)
    {
        case CallingActivityInterface.MAIN_ACTIVITY:
        {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
        ...
    }
}

This way the drawer is closed with no animation when I return to MainActivity regardless of whether I use the up button or the back button. There are probably better ways to do this. My app is relatively simple at the moment and this works, but I await a more effective method if anyone has one.

Hamfurd answered 10/11, 2014 at 0:18 Comment(0)
E
2

Why the hassle? Simply close the Drawer when clicking a drawer item. That's how it's done in the official Google Play app.

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         drawerLayout.closeDrawer(GravityCompat.START, false);
         selectItem(position); 
    }
}
Eucharis answered 22/4, 2017 at 12:30 Comment(2)
Why the hassle? Because closeDrawer didn't exist until issuetracker.google.com/issues/37087029Preprandial
@Eucharis "Why the hassle? Simply close the Drawer when clicking a drawer item", this is the best answer, it worked for me, althouh mine worked without the second argument (false) which had to be removed. Thumbs up buddy!Corniculate
S
2

if you are in android 13 latest version using kotlin want to close drawer when you press back button and if the drawer is open and you are facing problem that onBackPressed() is not even getting called by the system.

val callback = onBackPressedDispatcher.addCallback(this, false) {
        drawerLayout.closeDrawer(GravityCompat.START)
    }

    drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {

        override fun onDrawerOpened(drawerView: View) {
            callback.isEnabled = true
        }

        override fun onDrawerClosed(drawerView: View) {
            callback.isEnabled = false
        }

        override fun onDrawerSlide(drawerView: View, slideOffset: Float) = Unit
        override fun onDrawerStateChanged(newState: Int) = Unit
    })
Speak answered 19/7, 2023 at 13:38 Comment(0)
I
1

You will probably want to make sure the navigation draw is always closed when the activity is opened. Use this to do that:

@Override
public void onResume(){
    mDrawerList.closeDrawer(Gravity.LEFT);
}
Intent answered 9/11, 2014 at 22:11 Comment(1)
Thanks, this works, but there is a small problem. Navigating back from the ActionBar takes me to the screen I see on startup, with no drawer visible at all. Using the back button will close the drawer, but I still see a glimpse of it while it is closing. The docs say it is "animated out of view." How can I get rid of the animation so it is not visible at all?Hamfurd
C
1

JETPACK COMPOSE

For someone that using jetpack compose.

use this code in your scaffold:

BackHandler(enabled = drawerState.isOpen) {

     scope.launch { drawerState.close() }
}

complete version:

val scope = rememberCoroutineScope()
val drawerState = rememberDrawerState(DrawerValue.Closed)

Scaffold(

    topBar = {},

    bottomBar = {},

    snackbarHost = {},

    content = {

      ...

        BackHandler(enabled = drawerState.isOpen) {

            scope.launch { drawerState.close() }
        }
    },
    ...

)
Cerallua answered 8/1, 2023 at 19:46 Comment(0)
S
0

simple sample:

Drawer resultDrawer;

public void onBackPressed(){
    if (this.resultDrawer.isDrawerOpen()) {    
        this.resultDrawer.closeDrawer();    
    } else {    
        super.onBackPressed();    
    }
}
Solent answered 9/11, 2014 at 21:52 Comment(0)
C
0

With androidx.drawerlayout:drawerlayout:1.1.0 or higher, you can keep it simple using isOpen and close().

// YourActivity.kt
override fun onBackPressed() {
    if (drawerLayout.isOpen) {
        drawerLayout.close()
    } else {
        super.onBackPressed()
    }
}
Cullum answered 20/3, 2021 at 17:13 Comment(0)
I
0

This how i did it:

@Override
    public void onBackPressed() {

        if(drawerLayout.isDrawerOpen(navigationView)){
            drawerLayout.closeDrawer(Gravity.LEFT);
        }else{
            super.onBackPressed();
        }
    }
Intrastate answered 30/10, 2021 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.