Home » Android » android – Add MenuItem to NavigationView with Icon and Title?

android – Add MenuItem to NavigationView with Icon and Title?

Posted by: admin June 15, 2020 Leave a comment


Right now I am trying to implement the DrawerLayout/NavigationView from the new Design Support libary (22.2.1) into my application. I already searched on the internet and especially on stackoverflow how to add a MenuItem to a Submenu with Icon and Title. I know that it is possible to add a menuitem with a title or icon.

like that:

        Menu m = mNavigationView.getMenu();

But that is only a MenuItem with a Title,without Icon.
Is it possible to add a MenuItem with a Title and Icon?

How to&Answers:

First get the Menu from the NavigationView:

Menu menu = mNavigationView.getMenu();

Then add your item to the menu, remember to get the return MenuItem so you can add the icon later:

MenuItem item = menu.add(groupId, menuItemId, Order, "Menu Item 1 Title");
item.setIcon(R.drawable.ic_some_menu_item_icon); // add icon with drawable resource


create menu as

<menu xmlns:android="http://schemas.android.com/apk/res/android">

     android:title="Home" />

 <item android:title="Sub items">
            android:title="Sub item 1" />
            android:title="Sub item 2" />

here is sample app



For adding a menu item grammatically with icon, you need to first add a menu with id and title, using this

 menu.add( groupId, menuItemId, Order, "title" );

after this get this item using id and setIcon.

 menu.findItem( menuItemId ).setIcon( R.drawable.ic_add_black );


I found easier way to change navigation view ( work with both submenu and menu). You can re-inflate NavigationViewat runtime with 2 lines of code. In this example i re-inflate with new_navigation_drawer_items.xml when user successfully logged-in

navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.logged_in_navigation_drawer_items); //inflate new items.

When user log out just re-inflate again with logged_out_navigation_drawer_items.xml

navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.logged_out_navigation_drawer_items); //inflate new items.

So it actually re-inflate items but not add new items to existed one. Just create your own menu.xml