Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a submenu with radio buttons in Android?

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?

like image 709
Stan Avatar asked May 26 '12 17:05

Stan


People also ask

How to create menu and subMenu in Android?

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.

Can we select multiple radio buttons Android?

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.

What callback method is used to create a context menu?

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.


1 Answers

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>
like image 78
Martin Pfeffer Avatar answered Sep 25 '22 09:09

Martin Pfeffer