12

I want to hide a menu item in navigation drawer menu and show it depending on the type of the user that is using the application according to code below menu item is returning null:

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    MenuItem target = (MenuItem)drawer.findViewById(R.id.nav_target);

    target.setVisible(false);
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Convict Moody
  • 781
  • 1
  • 9
  • 28

2 Answers2

40

Fixed it by creating a menu and using

menu.findItem(R.id.nav_target)

as @droid8421 suggested.

Fixed Code:

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

Menu menu =navigationView.getMenu();

MenuItem target = menu.findItem(R.id.nav_target);

target.setVisible(false);
Convict Moody
  • 781
  • 1
  • 9
  • 28
0

I was facing the same issue when developing an application that has two productFlavours (Free & Premium)

What I did to show the BuyProVersion Menu item in the Free Version and disable it in the Premium Version was:

Menu menu = navigationView.getMenu();
MenuItem buyPro = 
menu.findItem(R.id.buy_pro_version)
if(buildConfig.FLAVOR.equalsIgnorCase("paid")){
    //Logic for disabling BuyProVersion Menu item
buyPro.setVisible(false)
}else {
    buyPro.setVisible(true)
}

I hope it helps someone someday. Make sure you set up productFlavours in your build.gradle

Obot Ernest
  • 412
  • 8
  • 19