0

I have to hide menu item dynamically. Below I have written menu.xml file code

  <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <group android:checkableBehavior="single" android:id="@+id/menu1">
            <item
                android:id="@+id/Admin"
                android:title="Admin" />
        </group>
        <group android:checkableBehavior="single" android:id="@+id/menu2">
            <item
                android:id="@+id/Worker"
                android:title="Worker" />
        </group>
    </menu>

I have to hide Admin menu while logging with Worker.

Shekhar Jadhav
  • 1,035
  • 9
  • 20
  • 1
    Possible duplicate of [Set visibility in Menu programmatically android](https://stackoverflow.com/questions/9030268/set-visibility-in-menu-programmatically-android) –  Nov 07 '17 at 05:43
  • Possible duplicate of [How to hide option menu?](https://stackoverflow.com/questions/32175845/how-to-hide-option-menu) – fluffyBatman Nov 07 '17 at 05:51

4 Answers4

6

Below changes it will help you to hide/show menu in dynamically on your program

private Menu menuList;

.
.
.

@Override

 public boolean onCreateOptionsMenu(Menu menu)
{

    this.menuList = menu;
    getMenuInflater().inflate(R.menu.options, menu);
    return true;
}

// ........

private void hideMenu()
{

    MenuItem item = menuList.findItem(R.id.submitmenu);
    item.setVisible(false);
}


private void showMenu()
{

    MenuItem item = menuList.findItem(R.id.submitmenu);
    item.setVisible(true);
}
Sos.
  • 914
  • 10
  • 14
vendeeshwaran Chandran
  • 1,383
  • 1
  • 13
  • 13
3

Try this .

 @Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem menu1 = menu.findItem(R.id.menu1);
    menu1.setVisible(false);
    MenuItem menu2 = menu.findItem(R.id.menu2);
    menu2.setVisible(false);
    return true;
}
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
3

Call the method wherever you want..

private void hideItem()
    {

        Menu nav_Menu = navigationView.getMenu();
        nav_Menu.findItem(R.id.nav_adduser).setVisible(false);
    }

I hope this may help you

Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
1

Try this

MenuItem menuItemLogout = nvDrawer.getMenu().findItem(R.id.nav_logout);
menuItemLogout.setVisible(true);
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
Ankush Bist
  • 1,862
  • 1
  • 15
  • 32