Soren Stoutner Soren Stoutner - 1 year ago 118
Android Question

How to programatically disable and enable items every time an Android NavigationView is displayed

I am moving some menu items from the options menu to the navigation menu. My app uses a NavigationView that is populated by a menu as described at

One of the items calls

on the
in the main activity. When it was placed in the options menu, it was only enabled if
. Otherwise, it was disabled (grayed out). To accomplish this,
included the command:


is called every time the options menu is about to be displayed, this would update the status of the menu item to correctly reflect the state of the

However, I have not been able to replicate this behavior with the NavigationView. Is there a method or class similar to
that is called each time the NavigationView is prepared?

PS. Other people who have addressed similar questions have always referred to using a ListView, which was an older method of populating a navigation drawer. This question specifically relates to using a NavigationView with a menu.

Answer Source

The answer to this question is to add a DrawerListener and override onDrawerStateChanged.

// Create the navigation drawer.
drawerLayout = (DrawerLayout) findViewById(;
// The `DrawerTitle` identifies the drawer in accessibility mode.
drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));

// Listen for touches on the navigation menu.
final NavigationView navigationView = (NavigationView) findViewById(;

// Get handles for `navigationMenu` and the back and forward menu items.  The menu is zero-based, so item 1 and 2 and the second and third items in the menu.
final Menu navigationMenu = navigationView.getMenu();
final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);

// The `DrawerListener` allows us to update the Navigation Menu.
drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
    public void onDrawerSlide(View drawerView, float slideOffset) {

    public void onDrawerOpened(View drawerView) {

    public void onDrawerClosed(View drawerView) {

    public void onDrawerStateChanged(int newState) {
        // Update the back and forward menu items every time the drawer opens.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download