Я хочу добавить имя идентификатора, чтобы изменить фрагменты с помощью onNavigationItemSelected, но я не могу добавить идентификатор программно. Мне нужно что-то вроде "установить идентификатор ()", как в показанном коде
menu.add("menu_name");
menu.getItem(i).setId("nav_item"+(i));
menu.getItem(i).setIcon(idIcon);
Вы можете использовать добавить (int groupId, int itemId, int порядок, CharSequence название), второй параметр - это идентификатор пункта меню. Например:
menu.add(0, 2, 0, "menu name");// 2 is the id value.
Из Menu.java есть такая сигнатура метода add():
/** * 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);
Используйте это так:
int newId = 100;
MenuItem newItem = menu.add(0, newId, 0, "New Item");
Возвращает новый пункт меню.
Вы, вероятно, собираетесь использовать его, чтобы проверить, какой пункт меню был нажат. Поэтому вы должны убедиться, что этот идентификатор не совпадает с идентификаторами других пунктов меню.
Может ли этот идентификатор быть любым числом? Или мне о чем-то беспокоиться?