【问题标题】:How to add an id to the menu item programmatically in android如何在android中以编程方式将id添加到菜单项
【发布时间】:2018-11-27 21:50:32
【问题描述】:

我想添加一个 id 名称以使用 onNavigationItemSelected 更改片段,但我无法以编程方式添加 id。 我需要类似 "setId ()" 的东西,如代码所示

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

【问题讨论】:

    标签: android menu menuitem navigationview


    【解决方案1】:

    你可以使用add (int groupId, int itemId, int order, CharSequence title),第二个参数是菜单项的id。 例如:

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

    【讨论】:

      【解决方案2】:

      来自Menu.javaadd() 方法的这个签名:

      /**
       * 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");
      

      它返回新的菜单项。

      【讨论】:

      • 这个id可以是任意数字吗?还是我应该担心什么?
      • 您可能会使用它来检查单击了哪个菜单项。所以你必须确保这个 id 在其他菜单项 id 中是不一样的。
      猜你喜欢
      • 2013-12-16
      • 1970-01-01
      • 2013-10-29
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      相关资源
      最近更新 更多