Add MenuItem to NavigationView with Icon and Title?

pimato picture pimato · Jul 24, 2015 · Viewed 8.4k times · Source

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();
        m.add(R.id.groupID,R.id.menuItemID,orderNumber,"title");

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

Answer

Grace Coder picture Grace Coder · Dec 23, 2015

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