动态地将项添加到PopupMenu组

时间:2018-01-03 15:10:55

标签: java android menuitem popupmenu

我有一个 XML菜单

<?xml version="1.0" encoding="utf-8"?>

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

    <group
        android:id="@+id/orders_filter_messages_group"
        android:checkableBehavior="all">

        <item
            android:id="@+id/orders_filter_messages_channel_1"
            android:title="@string/orders_filter_messages_channel_1" />

        <item
            android:id="@+id/orders_filter_messages_channel_2"
            android:title="@string/orders_filter_messages_channel_2" />

        <item
            android:id="@+id/orders_filter_messages_channel_3"
            android:title="@string/orders_filter_messages_channel_3" />

    </group>

</menu>

我想在 orders_filter_messages_group 中添加一些项目,所以我做了:

this.filterMenu = new PopupMenu(this.getActivity(), this.getActivity().findViewById(R.id.orders_filter_button));
this.filterMenu.inflate(R.menu.popup_orders_filter);

for (Channel channel : channels)
    this.filterMenu.getMenu().add(R.id.orders_filter_messages_group, Menu.NONE, Menu.NONE, channel.getName());

结果是PopupMenu上的项目添加得很好,但是在列表的末尾(组外)添加了项目,因此它们不可检查。

如果我更改了order参数,我可以设法将它们放在正确的位置,但是它们不在组内并且仍然无法检查。

1 个答案:

答案 0 :(得分:2)

getMenu().add()方法返回一个MenuItem。有了这个,你就可以完全控制...... 试试这个:

MenuItem addedMenuItem = this.filterMenu.getMenu().add(R.id.orders_filter_messages_group, Menu.NONE, Menu.NONE, channel.getName());
addedMenuItem.setCheckable(true);

要在PopupMenu的onClickListener中访问它,请在add()方法中添加唯一ID,而不是Menu.NONE

final int uniqueID = 12345;
MenuItem addedMenuItem = this.filterMenu.getMenu().add(R.id.orders_filter_messages_group, uniqueID, Menu.NONE, channel.getName());

//and in the onClickListener
filterMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick (MenuItem item) {
                if(item.getItemId() == uniqueID) //TODO
                return false;
            }
        });


希望这会对你有所帮助!