How to close navigation drawer when an item is pressed from it?
Asked Answered
M

7

89

Ideally navigation drawer should get closed once some item has been pressed from it, but its not happening automatically. How to do it ? Thanks!

Macilroy answered 5/10, 2013 at 5:56 Comment(1)
Which libary do you use to get the navigation drawer?Iroquois
M
254

Got it!

private DrawerLayout mDrawerLayout;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.closeDrawers();

Working perfectly fine.

Macilroy answered 5/10, 2013 at 7:49 Comment(3)
Can it be closed without animation?Linkous
Hamzeh - mDrawerLayout.closeDrawer(Gravity.LEFT, false); would result in closing it without animationBoschbok
mDrawerLayout.closeDrawer(GravityCompat.START, false);Pigeonwing
C
13

For me this one worked -

mDrawerLayout.closeDrawer(Gravity.START, false);
Chittagong answered 21/2, 2018 at 3:19 Comment(0)
S
9
DrawerLayout mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout)

closeDrawer(); // called when you want to close

public void closeDrawer() {
  if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
    mDrawerLayout.closeDrawer(GravityCompat.START);
  }
}
Sluggard answered 26/6, 2019 at 5:57 Comment(0)
S
6
closeDrawer();//when you want to call

public void closeDrawer() {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }
}
Sluggard answered 26/6, 2019 at 5:53 Comment(0)
G
4

If you have mDrawerLayout as your drawer layout, you can close it when it is open.

@Override
public void onBackPressed() {
    if (this.mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        this.mDrawerLayout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
Gilthead answered 2/2, 2020 at 14:19 Comment(0)
H
3

On the right bottom of onNavigationItemSelected where the switch case ends you should right this. mDrawerLayout.closeDrawers();

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){

        }
   mDrawerLayout.closeDrawers();
   return true;
}
Highminded answered 20/7, 2019 at 15:23 Comment(0)
S
1

This work,kotlin code

drawerLayout.closeDrawer(GravityCompat.START)
Stator answered 25/8, 2021 at 16:54 Comment(1)
Hi, thanks for your answer, but it's a duplicate of multiple other answer such as this oneAntihelix

© 2022 - 2024 — McMap. All rights reserved.