47
<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.

Jonik
  • 80,077
  • 70
  • 264
  • 372
user2331095
  • 6,577
  • 8
  • 36
  • 56

5 Answers5

108

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

N J
  • 27,217
  • 13
  • 76
  • 96
9

I think you should first get the menu like this:

navigationView.getMenu().findItem(R.id.login).setVisible(false);

The main aspect of this code is calling navigationView.getMenu() to get the menu from this you will have a reference of current inflated menu and call findViewById() and after that you can whatever you what.

For Group of item ex:-

<group
android:id="@+id/group_1"
android:checkableBehavior="single"
android:visible="false">
...

and then you can control this using :-

navigationView.getMenu().setGroupVisible(R.id.group_1, true)
amit kumar
  • 291
  • 1
  • 6
6

just use below way

nav_draw = (NavigationView) findViewById(R.id.nav_draw);
nav_draw.getMenu().findItem(R.id.navigation_item_1).setVisible(false);
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
0

You can get the item by

navigationView.Menu.GetItem(menu_index)
MSR
  • 2,731
  • 1
  • 14
  • 24
0
View navHeader=navigationView.getHeaderView(0);[![enter image description here][1]][1]

navMenu=navigationView.getMenu();

  1. List item

    //work for login and logout menu
    if (MyPreferences.getBoolean(BaseActivity.this,ConstantValues.KEY_IS_LOGIN)){
        navMenu.getItem(0).setVisible(false);
        navMenu.getItem(9).setVisible(true);
    }else {
        navMenu.getItem(0).setVisible(true);
        navMenu.getItem(9).setVisible(false);
    }
    
chandan raj
  • 51
  • 1
  • 5