Add MenuItem to NavigationView with icon and title?

Now I'm trying to implement DrawerLayout / NavigationView from the new design support library (22.2.1) in my application. I have already searched on the Internet and especially in stackoverflow how to add MenuItem to a submenu with an icon and a title. I know that you can add a menu item that says or .

like this:

Menu m = mNavigationView.getMenu(); m.add(R.id.groupID,R.id.menuItemID,orderNumber,"title"); 

But this is only a MenuItem with a caption, without an icon. Can I add a MenuItem with the Title and icon?

+5
source share
4 answers

First select a menu from NavigationView:

 Menu menu = mNavigationView.getMenu(); 

Then add your item to the menu, remember to return the returned 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 
+9
source

create menu as

 <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_dashboard" android:title="Home" /> <item android:title="Sub items"> <menu> <item android:icon="@drawable/ic_dashboard" android:title="Sub item 1" /> <item android:icon="@drawable/ic_forum" android:title="Sub item 2" /> </menu> </item> </menu> 

Here is an example application

https://github.com/chrisbanes/cheesesquare

+3
source

To add a menu item grammatically with an icon, you first need to add a menu with an identifier and a name using this

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

after that get this element using id and setIcon.

  menu.findItem( menuItemId ).setIcon( R.drawable.ic_add_black ); 
+2
source

I found an easier way to change the navigation view (working with submenus and menus). You can re-inflate the NavigationView at run time with two lines of code. In this example, I re-inflate with new_navigation_drawer_items.xml when the user successfully logged in

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

When the user logs out, inflate it 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. 

Thus, he actually inflates the elements, but does not add new objects to the existing one. Just create your own menu.xml

0
source

All Articles