Search code examples
androidmenumenuitemnavigationview

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);

Solution

  • 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.