Greelings
Greelings

Reputation: 5434

Add an item to a group of a PopupMenu dynamically

I have a XML menu :

<?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>

I would like to add some items to the orders_filter_messages_group, so I did :

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

The result is that the items are well added on the PopupMenu, BUT the are added on the end of the list (outside of the group), and consequently, they are not checkable.

If I change the order parameter, I can manage to position them in the right place, but they stay outside of the group and remain uncheckable.

Upvotes: 3

Views: 2396

Answers (1)

BEAGLE ENTERTAIN
BEAGLE ENTERTAIN

Reputation: 156

The getMenu().add() method returns a MenuItem. With that you get full control... Try this:

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

To access it in the PopupMenu's onClickListener, add a unique ID inside the add() method instead of 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;
            }
        });


Hope this will help you!

Upvotes: 3

Related Questions