Checkable menu items

Any menu item can be used as an interface for turning options on and off. This can be indicated with a checkbox for stand-alone options, or radio buttons for groups of mutually exlusive options (see the screenshot, to the right).

Note: Menu items in the Icon Menu cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, then you must personally indicate the state by swapping the icon and/or text each time the state changes between on and off.

To make a single item checkable, use the setCheckable() method, like so:

menu.add(0, VIBRATE_SETTING_ID, 0, "Vibrate") .setCheckable(true);

This will display a checkbox with the menu item (unless it's in the Icon Menu). When the item is selected, the onOptionsItemSelected() callback is called as usual. It is here that you must set the state of the checkbox. You can query the current state of the item with isChecked() and set the checked state with setChecked() . Here's what this looks like inside the onOptionsItemSelected() callback:

switch (item.getItemId()) { case VIBRATE_SETTING_ID:

if (item.isChecked()) item.setChecked(false); else item.setChecked(true); return true;

To make a group of mutually exclusive radio button items, simply assign the same group ID to each menu item and call setGroupCheckable() . In this case, you don't need to call setCheckable() on each menu items, because the group as a whole is set checkable. Here's an example of two mutually exclusive options in a Submenu:

SubMenu subMenu = menu.addSubMenu("Color"); subMenu.add(COLOR_MENU_GROUP, COLOR_RED_ID, 0, "Red"); subMenu.add(COLOR_MENU_GROUP, COLOR_BLUE_ID, 0, "Blue"); subMenu.setGroupCheckable(COLOR_MENU_GROUP, true, true);

In the setGroupCheckable() method, the first argument is the group ID that we want to set checkable. The second argument is whether we want the group items to be checkable. The last one is whether we want each item to be exclusively checkable (if we set this false, then all the items will be checkboxes instead of radio buttons). When the group is set to be exclusive (radio buttons), each time a new item is selected, all other are automatically de-selected.

Note: Checkable menu items are intended to be used only on a per-session basis and not saved to the device (e.g., the Map mode setting in the Maps application is not saved — screenshot above). If there are application settings that you would like to save for the user, then you should store the data using Preferences, and manage them with a PreferenceActivity.

0 0

Post a comment