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

AndroidNavigation Drawer

Android Problem Overview


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

Android Solutions


Solution 1 - Android

Got it!

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

Working perfectly fine.

Solution 2 - Android

For me this one worked -

mDrawerLayout.closeDrawer(Gravity.START, false);

Solution 3 - Android

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);
  }
}

Solution 4 - Android

closeDrawer();//when you want to call

public void closeDrawer() {
    if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }
}

Solution 5 - Android

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();
    }
}

Solution 6 - Android

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;
}

Solution 7 - Android

This work,kotlin code

drawerLayout.closeDrawer(GravityCompat.START)

Solution 8 - Android

drawerLayout.closeDrawer(GravityCompat.START);

This line of code work for me :) ps. It works for me in Java code but I think it can also work in Kotlin

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVipul JView Question on Stackoverflow
Solution 1 - AndroidVipul JView Answer on Stackoverflow
Solution 2 - AndroidA JView Answer on Stackoverflow
Solution 3 - AndroidAshifView Answer on Stackoverflow
Solution 4 - AndroidAshifView Answer on Stackoverflow
Solution 5 - AndroidM Shafaei NView Answer on Stackoverflow
Solution 6 - AndroidsubbuView Answer on Stackoverflow
Solution 7 - AndroidKaram KaramView Answer on Stackoverflow
Solution 8 - AndroidAngge D.View Answer on Stackoverflow