如何将项目添加到NavigationView中的菜单组

时间:2022-02-09 07:31:33

In a word game for Android I currently have a hardcoded menu inflated from left_drawer_menu.xml and consisting of 3 groups (my turn, opponent turn and finally other stuff):

在Android的文字游戏中,我目前有一个从left_drawer_menu.xml膨胀的硬编码菜单,包括3组(轮到我,对手回合,最后是其他东西):

如何将项目添加到NavigationView中的菜单组

mLeftDrawer = (NavigationView) findViewById(R.id.left_drawer);
mLeftDrawer.setNavigationItemSelectedListener(
        new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(final MenuItem menuItem) {
                Menu menu = mLeftDrawer.getMenu();

                if (menuItem.getGroupId() == R.id.my_move) {
                    menu.setGroupCheckable(R.id.my_move, true, true);
                    menu.setGroupCheckable(R.id.his_move, false, false);
                    menu.setGroupCheckable(R.id.extras, false, false);
                } else if (menuItem.getGroupId() == R.id.his_move) {
                    menu.setGroupCheckable(R.id.my_move, false, false);
                    menu.setGroupCheckable(R.id.his_move, true, true);
                    menu.setGroupCheckable(R.id.extras, false, false);
                } else if (menuItem.getGroupId() == R.id.extras) {
                    menu.setGroupCheckable(R.id.my_move, false, false);
                    menu.setGroupCheckable(R.id.his_move, false, false);
                    menu.setGroupCheckable(R.id.extras, true, true);
                }

                menuItem.setChecked(true);
                mLeftItem = menuItem.getItemId();
                mDrawerLayout.closeDrawer(mLeftDrawer);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mLeftItem == R.id.start) {
                            startNewGame();
                        } 
                    }
                },DRAWER_CLOSE_DELAY);

                return true;
            }
        });

Now I am trying to change that menu dynamically.

现在我正在尝试动态更改该菜单。

I have SQLite instance containing all game data and use IntentService to read/write the database - that part works fine.

我有包含所有游戏数据的SQLite实例,并使用IntentService来读/写数据库 - 该部分工作正常。

My current difficulty is: with the following code, the new items are added outside the R.id.my_move group:

我目前的困难是:使用以下代码,新项目将添加到R.id.my_move组之外:

if (mLeftItem == R.id.start) {
    startNewGame();

    Random r = new Random();
    int i = r.nextInt(100);
    menu.add(R.id.my_move, i, i, "Item " + i);   // why is my_move ignored?
} 

如何将项目添加到NavigationView中的菜单组

UPDATE:

As a further test I have tried assigning even and not even items to 2 separate groups with this code:

作为进一步的测试,我尝试使用以下代码将偶数项甚至是偶数项分配给2个单独的组:

Random r = new Random();
int i = r.nextInt(100);
int group = 1 + (i % 2); // can be 1 or 2
menu.add(group, i, i, "Item " + i);

However the result looks chaotic:

但结果看起来很混乱:

如何将项目添加到NavigationView中的菜单组

Also I have discovered the (probably already fixed?) Issue 176300 and wonder if maybe sub-menus should be better used instead of menu groups?

另外我发现(可能已经修复了?)问题176300并想知道是否应该更好地使用子菜单而不是菜单组?

3 个解决方案

#1


30  

On checking MenuItemImpl source code

在检查MenuItemImpl源代码时

     ...
     *    @param group Item ordering grouping control. The item will be added after
     *            all other items whose order is <= this number, and before any
     *            that are larger than it. This can also be used to define
     *            groups of items for batch state changes. Normally use 0.
     ...

    MenuItemImpl(MenuBuilder menu, int group, int id, int categoryOrder, int ordering,
        CharSequence title, int showAsAction) {

So you should define ordering in your xml (give same order to items in one group and increment in each following group)

因此,您应该在xml中定义排序(对一个组中的项目赋予相同的顺序,并在每个后续组中增加)

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:id="@+id/my_move" android:checkableBehavior="single">
        <item
            android:orderInCategory="0"
            android:id="@+id/game1"
            android:icon="@drawable/ic_stars_black_24dp"
            android:title="Game #1" />
        <item
            android:orderInCategory="0"
            android:id="@+id/game2"
            android:icon="@drawable/ic_stars_black_24dp"
            android:title="Game #2" />
    </group>
    <group android:id="@+id/his_move" android:checkableBehavior="single">
        <item
            android:orderInCategory="1"
            android:id="@+id/game5"
            android:icon="@drawable/ic_clock_black_24dp"
            android:title="Game #5" />
        <item
            android:orderInCategory="1"
            android:id="@+id/game6"
            android:icon="@drawable/ic_clock_black_24dp"
            android:title="Game #6" />
        <item
            android:orderInCategory="1"
            android:id="@+id/game7"
            android:icon="@drawable/ic_clock_black_24dp"
            android:title="Game #7" />
    </group>
    .....

</menu>

and give an appropriate order value while adding the item in your code. So if you want to add the item at the end of first group, add it as:

并在代码中添加项目时提供适当的订单值。因此,如果要在第一组末尾添加项目,请将其添加为:

menu.add(R.id.my_move, Menu.NONE, 0, "Item1");

and if you want to add to second group, add it as:

如果要添加到第二组,请将其添加为:

menu.add(R.id.his_move, Menu.NONE, 1, "Item2");

The problem with your code could be that all items in the xml have default orderInCategory 0 and so the new item gets added after all these items.

您的代码的问题可能是xml中的所有项都具有默认的orderInCategory 0,因此在所有这些项之后添加新项。

UPDATE

To add icon use setIcon method for MenuItem

要添加图标,请使用MenuItem的setIcon方法

menu.add(R.id.my_move, Menu.NONE, 0, "Item1").setIcon(R.drawable.ic_stars_black_24dp);

#2


11  

如何将项目添加到NavigationView中的菜单组

I've solved it this way:

我用这种方式解决了这个问题:

  1. Set up the menu:

    设置菜单:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:title="my moves"
              android:id="@+id/submenu_1">
            <menu>
                <item
                    android:id="@+id/my_dummy_item_1"
                    android:icon="@drawable/ic_menu_camera"
                    android:title="Import" />
                <item
                    android:id="@+id/my_dummy_item_2"
                    android:icon="@drawable/ic_menu_gallery"
                    android:title="Gallery" />
                <item
                    android:id="@+id/add_item"
                    android:icon="@drawable/ic_menu_manage"
                    android:title="Add Item" />
            </menu>
        </item>
        <item android:title="opponent's moves"
              android:id="@+id/submenu_2">
            <menu>
                <item
                    android:id="@+id/opponent_dummy_item_1"
                    android:icon="@drawable/ic_menu_camera"
                    android:title="Import" />
                <item
                    android:id="@+id/opponent_dummy_item_2"
                    android:icon="@drawable/ic_menu_gallery"
                    android:title="Gallery" />
                <item
                    android:id="@+id/opponent_dummy_item_3"
                    android:icon="@drawable/ic_menu_manage"
                    android:title="Tools" />
            </menu>
        </item>
    </menu>
    
  2. In onNavigationItemSelected(), get MenuItem you want to expand by order id (or via findItem()), then get SubMenu from it and add new item into it:

    在onNavigationItemSelected()中,获取要通过订单ID(或通过findItem())扩展的MenuItem,然后从中获取SubMenu并向其中添加新项:

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
    
        if (id == R.id.add_item) {
            Random r = new Random();
            int i = r.nextInt(100);
            MenuItem myMoveGroupItem = navigationView.getMenu().getItem(0);
            // MenuItem myMoveGroupItem = navigationView.getMenu().findItem(R.id.submenu_1);  -- it also works!
            SubMenu subMenu = myMoveGroupItem.getSubMenu();
            subMenu.add("Item "+i);
        }
    
        return true;
    }
    

I hope, it helps

我希望,这有帮助

#3


1  

menu.add(R.id.my_move, i, i, "Item " + i);

You are also assigning the order (3rd param) as i. I am guessing that this is overriding the groupId. Try setting it as NONE as mentioned here

您也将订单(第3个参数)分配为i。我猜这是在覆盖groupId。尝试将其设置为NONE,如此处所述

menu.add(R.id.my_move, i, NONE, "Item " + i);

Edit: Maybe something like this

编辑:也许是这样的

MenuItem lastItem = menu.findItem(R.id.<lastItemId>);
int lastOrder= lastItem.getOrder();
menu.add(R.id.my_move, i, lastOrder-5, "Item " + i);

Order is a combination of category and order, so it might not be as straight forward as this.

订单是类别和订单的组合,因此可能不如此直截了当。

#1


30  

On checking MenuItemImpl source code

在检查MenuItemImpl源代码时

     ...
     *    @param group Item ordering grouping control. The item will be added after
     *            all other items whose order is <= this number, and before any
     *            that are larger than it. This can also be used to define
     *            groups of items for batch state changes. Normally use 0.
     ...

    MenuItemImpl(MenuBuilder menu, int group, int id, int categoryOrder, int ordering,
        CharSequence title, int showAsAction) {

So you should define ordering in your xml (give same order to items in one group and increment in each following group)

因此,您应该在xml中定义排序(对一个组中的项目赋予相同的顺序,并在每个后续组中增加)

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:id="@+id/my_move" android:checkableBehavior="single">
        <item
            android:orderInCategory="0"
            android:id="@+id/game1"
            android:icon="@drawable/ic_stars_black_24dp"
            android:title="Game #1" />
        <item
            android:orderInCategory="0"
            android:id="@+id/game2"
            android:icon="@drawable/ic_stars_black_24dp"
            android:title="Game #2" />
    </group>
    <group android:id="@+id/his_move" android:checkableBehavior="single">
        <item
            android:orderInCategory="1"
            android:id="@+id/game5"
            android:icon="@drawable/ic_clock_black_24dp"
            android:title="Game #5" />
        <item
            android:orderInCategory="1"
            android:id="@+id/game6"
            android:icon="@drawable/ic_clock_black_24dp"
            android:title="Game #6" />
        <item
            android:orderInCategory="1"
            android:id="@+id/game7"
            android:icon="@drawable/ic_clock_black_24dp"
            android:title="Game #7" />
    </group>
    .....

</menu>

and give an appropriate order value while adding the item in your code. So if you want to add the item at the end of first group, add it as:

并在代码中添加项目时提供适当的订单值。因此,如果要在第一组末尾添加项目,请将其添加为:

menu.add(R.id.my_move, Menu.NONE, 0, "Item1");

and if you want to add to second group, add it as:

如果要添加到第二组,请将其添加为:

menu.add(R.id.his_move, Menu.NONE, 1, "Item2");

The problem with your code could be that all items in the xml have default orderInCategory 0 and so the new item gets added after all these items.

您的代码的问题可能是xml中的所有项都具有默认的orderInCategory 0,因此在所有这些项之后添加新项。

UPDATE

To add icon use setIcon method for MenuItem

要添加图标,请使用MenuItem的setIcon方法

menu.add(R.id.my_move, Menu.NONE, 0, "Item1").setIcon(R.drawable.ic_stars_black_24dp);

#2


11  

如何将项目添加到NavigationView中的菜单组

I've solved it this way:

我用这种方式解决了这个问题:

  1. Set up the menu:

    设置菜单:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:title="my moves"
              android:id="@+id/submenu_1">
            <menu>
                <item
                    android:id="@+id/my_dummy_item_1"
                    android:icon="@drawable/ic_menu_camera"
                    android:title="Import" />
                <item
                    android:id="@+id/my_dummy_item_2"
                    android:icon="@drawable/ic_menu_gallery"
                    android:title="Gallery" />
                <item
                    android:id="@+id/add_item"
                    android:icon="@drawable/ic_menu_manage"
                    android:title="Add Item" />
            </menu>
        </item>
        <item android:title="opponent's moves"
              android:id="@+id/submenu_2">
            <menu>
                <item
                    android:id="@+id/opponent_dummy_item_1"
                    android:icon="@drawable/ic_menu_camera"
                    android:title="Import" />
                <item
                    android:id="@+id/opponent_dummy_item_2"
                    android:icon="@drawable/ic_menu_gallery"
                    android:title="Gallery" />
                <item
                    android:id="@+id/opponent_dummy_item_3"
                    android:icon="@drawable/ic_menu_manage"
                    android:title="Tools" />
            </menu>
        </item>
    </menu>
    
  2. In onNavigationItemSelected(), get MenuItem you want to expand by order id (or via findItem()), then get SubMenu from it and add new item into it:

    在onNavigationItemSelected()中,获取要通过订单ID(或通过findItem())扩展的MenuItem,然后从中获取SubMenu并向其中添加新项:

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
    
        if (id == R.id.add_item) {
            Random r = new Random();
            int i = r.nextInt(100);
            MenuItem myMoveGroupItem = navigationView.getMenu().getItem(0);
            // MenuItem myMoveGroupItem = navigationView.getMenu().findItem(R.id.submenu_1);  -- it also works!
            SubMenu subMenu = myMoveGroupItem.getSubMenu();
            subMenu.add("Item "+i);
        }
    
        return true;
    }
    

I hope, it helps

我希望,这有帮助

#3


1  

menu.add(R.id.my_move, i, i, "Item " + i);

You are also assigning the order (3rd param) as i. I am guessing that this is overriding the groupId. Try setting it as NONE as mentioned here

您也将订单(第3个参数)分配为i。我猜这是在覆盖groupId。尝试将其设置为NONE,如此处所述

menu.add(R.id.my_move, i, NONE, "Item " + i);

Edit: Maybe something like this

编辑:也许是这样的

MenuItem lastItem = menu.findItem(R.id.<lastItemId>);
int lastOrder= lastItem.getOrder();
menu.add(R.id.my_move, i, lastOrder-5, "Item " + i);

Order is a combination of category and order, so it might not be as straight forward as this.

订单是类别和订单的组合,因此可能不如此直截了当。