I have a problem in a simple case (at least, it looks like so). I need to create a submenu for a context menu dynamically and provide each item with a radiobox. I made a lot of trials. When I call menu.setGroupCheckable(0, true, true)
, where 0 is by default the menu itself, it displays radio buttons to the right on every menu item as expected, but I need this for submenu. So I have the following code:
SubMenu sub = menu.addSubMenu(R.string.name);
int count = 1000;
for(String e : someList)
{
MenuItem item = sub.add(1, count, count, e);
count++;
}
menu.setGroupCheckable(1, true, true);
In this case I don't see neither radioboxes, nor checkboxes in the submenu. Then I wrote the following code:
SubMenu sub = menu.addSubMenu(R.string.name);
int count = 1000;
for(String e : someList)
{
MenuItem item = sub.add(1, count, count, e);
item.setCheckable(true);
count++;
}
menu.setGroupCheckable(1, true, true);
This makes the submenu to have a checkbox in every item, and the checkboxes work exclusively, but I want radioboxes, because they look more intuitively for exclusive selection.
So, how can this be accomplished?
You can add submenus using the add submenu() method. It supports the same parameters as the add method used to add normal Menu Items, enabling you to specify a group, unique identifier, and text string for each submenu.
To create each radio button option, create a RadioButton in your layout. However, because radio buttons are mutually exclusive, you must group them together inside a RadioGroup . By grouping them together, the system ensures that only one radio button can be selected at a time.
To create a context menu, you must override the Activity's context menu callback methods: onCreateContextMenu() and onContextItemSelected() . Inside the onCreateContextMenu() callback method, you can add menu items using one of the add() methods, or by inflating a menu resource that was defined in XML.
Set the checkableBehavior in xml to single. Here is some code:
<menu>
<group android:id="@+id/group"
android:checkableBehavior="single">
<item android:id="@+id/menu_sort_by_name"
android:title="@string/action_sort_by_name"/>
<item android:id="@+id/menu_sort_by_last_edit"
android:title="@string/action_sort_by_last_edit"/>
</group>
</menu>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With