How can I get menu item in NavigationView?

user2331095 picture user2331095 · Jul 7, 2015 · Viewed 27.9k times · Source
<android.support.design.widget.NavigationView
    android:id="@+id/drawer_nav"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"
    app:headerLayout="@layout/drawer_header"
    app:menu="@menu/menu_drawer"
    />

I am using android.support.design.library for material design.

What I want is to hide some menu items when the user is not logged-in.

Now I have trouble to get the menu item in NavigationView.

I have tried:

MenuItem logoutItem = (MenuItem) mNavigationView.findViewById(R.id.menu_logout);
logoutItem.setVisible(false);

But it's not working.

How can I do this?

Thanks.

Answer

N J picture N J · Jul 7, 2015

You can get that by method of NavigationView.getMenu()

Menu menuNav = mNavigationView.getMenu();

Then you can find specific item by

MenuItem logoutItem = menuNav.findItem(R.id.menu_logout);

See Official documentation for NavigationView