Search code examples
androidandroid-studionavigation-drawermenuitem

How to hide a navigation drawer menu item programmatically?


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);

Solution

  • 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);