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!

Vipul J
  • 6,641
  • 9
  • 46
  • 61

7 Answers7

251

Got it!

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

Working perfectly fine.

Christian
  • 21
  • 1
  • 3
  • 7
Vipul J
  • 6,641
  • 9
  • 46
  • 61
13

For me this one worked -

mDrawerLayout.closeDrawer(Gravity.START, false);
A J
  • 4,542
  • 5
  • 50
  • 80
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);
  }
}
Ashif
  • 441
  • 5
  • 12
5
closeDrawer();//when you want to call

public void closeDrawer() {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }
}
shb
  • 5,957
  • 2
  • 15
  • 32
Ashif
  • 441
  • 5
  • 12
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();
    }
}
M Shafaei N
  • 409
  • 3
  • 6
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;
}
1

This work,kotlin code

drawerLayout.closeDrawer(GravityCompat.START)
AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
  • Hi, thanks for your answer, but it's a duplicate of multiple other answer such as [this one](https://stackoverflow.com/a/56766056/10952503) – Elikill58 Aug 31 '21 at 09:13