简体   繁体   中英

How to add an id to the menu item programmatically in android

I want to add a id name to get to change the fragments with onNavigationItemSelected, but I can not add an id programmatically. I need something like "setId ()" as in the code shown

menu.add("menu_name");
menu.getItem(i).setId("nav_item"+(i));
menu.getItem(i).setIcon(idIcon);

You could use add (int groupId, int itemId, int order, CharSequence title) , the second parameter is the id of menu item. for example:

menu.add(0, 2, 0, "menu name");// 2 is the id value.

From Menu.java there is this signature of the add() method:

 /** * Add a new item to the menu. This item displays the given title for its * label. * * @param groupId The group identifier that this item should be part of. * This can be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param title The text to display for the item. * @return The newly added menu item. */ 
public MenuItem add(int groupId, int itemId, int order, CharSequence title);

Use it like this:

int newId = 100;
MenuItem newItem = menu.add(0, newId, 0, "New Item");

It returns the new menu item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM