Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 632
Convict Moody Avatar asked Feb 26 '16 20:02

Convict Moody


People also ask

How do I hide a menu item?

Get a MenuItem pointing to such item, call setVisible on it to adjust its visibility and then call invalidateOptionsMenu() on your activity so the ActionBar menu is adjusted accordingly. Save this answer.

How do I hide the bottom item in navigation?

Touch “Settings” -> “Display” -> “Navigation bar” -> “Buttons” -> “Button layout”. Choose the pattern in “Hide navigation bar” -> When the app opens, the navigation bar will be automatically hidden and you can swipe up from the bottom corner of the screen to show it.

What is a DrawerLayout?

DrawerLayout acts as a top-level container for window content that allows for interactive "drawer" views to be pulled out from one or both vertical edges of the window.

What is NavigationView in Android?

com.google.android.material.navigation.NavigationView. Represents a standard navigation menu for application. The menu contents can be populated by a menu resource file. NavigationView is typically placed inside a DrawerLayout .


1 Answers

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);
like image 54
Convict Moody Avatar answered Nov 03 '22 14:11

Convict Moody