Login     Sign Up
Cyril Sermon (@admin)
10 months ago

To define a menu for an Activity, override its onCreateOptionsMenu method. This method is triggered the first time an Activity’s menu is displayed.

The onCreateOptionsMenu receives a Menu object as a parameter. You can store a reference to, and con-tinue to use, the Menu reference elsewhere in your code until the next time that onCreateOptionsMenu is called.

You should always call through to the base implementation as it automatically includes additional sys-tem menu options where appropriate.

Use the add method on the Menu object to populate your menu. For each Menu Item, you must specify:

❑A group value to separate Menu Items for batch processing and ordering❑A unique identifier for each Menu Item. For efficiency reasons, Menu Item selections are gener-ally handled by the onOptionsItemSelected event handler, so this unique identifier is impor-tant to determine which Menu Item was pressed. It is convention to declare each menu ID as a private static variable within the Activity class. You can use the Menu.FIRST static constant and simply increment that value for each subsequent item.

❑ An order value that defines the order in which the Menu Items are displayed

❑ The menu text, either as a character string or as a string resour

When you have finished populating the menu, return True to allow Android to display the men

The following skeleton code shows how to add a single item to an Activity men

static final private int MENU_ITEM = Menu.FIRS


public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu

// Group

int groupId = 

//Unique menu item identifier. Used for event handling. 
int menuItemId = MENU_ITE

//The order position of the it

int menuItemOrder = Menu.NON

//Text to be displayed for this menu item. int menuItemText = R.string.menu_ite

Create the menu item and keep a reference to it. MenuItem menuItem = menu.add(groupId, menuItemI

menuItemOrder, menuItemText

return tru

Like the Menu object, each Menu Item reference returned by a call to add is valid until the next call to onCreateOptionsMenu. Rather than maintaining a reference to each item, you can find a particular Menu Item by passing its ID into the Menu.findItem method

Menu Item Option

Android supports most of the traditional Menu Item options you’re probably familiar with, including icons, shortcuts, checkboxes, and radio buttons, as described belo

❑Checkboxes and Radio Buttons Checkboxes and radio buttons on Menu Items are visible in expanded menus and submenus, as shown in Figure 4-6. To set a Menu Item as a checkbox, use the setCheckable method. The state of that checkbox is controlled using setChecke

A radio button group is a group of items displaying circular buttons, where only one item can be selected at any given time. Checking one of these items will automatically unselect any other item in the same group, that is currently checked. To create a radio button group, assign the same group identifier to each item, then call Menu.setGroupCheckable, passing in that group identifier and setting the exclusive parameter to True.

Checkboxes are not visible in the icon menu, so Menu Items that feature checkboxes should be reserved for submenus and items that appear only in the expanded menu. The following code snippet shows how to add a checkbox and a group of three radio buttons:

// Create a new check box item.

menu.add(0, CHECKBOX_ITEM, Menu.NONE, “CheckBox”).setCheckable(true);

// Create a radio button group.

menu.add(RB_GROUP, RADIOBUTTON_1, Menu.NONE, “Radiobutton 1”); menu.add(RB_GROUP, RADIOBUTTON_2, Menu.NONE, “Radiobutton 2”); menu.add(RB_GROUP, RADIOBUTTON_3, Menu.NONE,

“Radiobutton 3”).setChecked(true);

menu.setGroupCheckable(RB_GROUP, true, true);

❑Shortcut Keys You can specify a keypad shortcut for a Menu Item using the setShortcut method. Each call to setShortcut requires two shortcut keys, one for use with the numeric keypad and a second to support a full keyboard. Neither key is case-sensitive.

The code below shows how to set a shortcut for both modes:

Add a shortcut to this menu item, ‘0’ if using the numeric keypad

or ‘b’ if using the full keyboard.

menuItem.setShortcut(‘0’, ‘b’);

❑Condensed Titles The icon menu does not display shortcuts or checkboxes, so it’s often neces-sary to modify its display text to indicate its state. The following code shows how to set the icon menu–specific text for a Menu Item:

menuItem.setTitleCondensed(“Short Title”);

❑Icons Icon is a drawable resource identifier for an icon to be used in the Menu Item. Icons are only displayed in the icon menu; they are not visible in the extended menu or submenus. The following snippet shows how to apply an icon to a Menu Item:


❑Menu Item Click Listener An event handler that will execute when the Menu Item is selected. For efficiency reasons, this is discouraged; instead, Menu Item selections should be handled by the onOptionsItemSelected handler as shown later in this section. To apply a click listener to a Menu Item, use the pattern shown in the following code snippet:

menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {

public boolean onMenuItemClick(MenuItem _menuItem) {

... execute click handling, return true if handled ... ] return true;



❑Intents An Intent assigned to a Menu Item is triggered when clicking a Menu Item isn’t han-dled by either a MenuItemClickListener or the Activity’s onOptionsItemSelected handler. When triggered, Android will execute startActivity, passing in the specified Intent. The fol-lowing code snippet shows how to specify an Intent for a Menu Item:

menuItem.setIntent(new Intent(this, MyOtherActivity.class));

Dynamically Updating Menu Items

By overriding your activity’s onPrepareOptionsMenu method, you can modify your menu based on the application state each time it’s displayed. This lets you dynamically disable/enable each item, set visibility, and modify text at runtime.

To modify Menu Items dynamically, you can either keep a reference to them when they’re created in the onCreateOptionsMenu method, or you can use menu.findItem as shown in the following skeleton code, where onPrepareOptionsMenu is overridden:


public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu);

MenuItem menuItem = menu.findItem(MENU_ITEM);

... modify menu items ... ] return true;


Handling Menu Selections

Android handles all of an Activity’s Menu Item selections using a single event handler, the onOptionsItemSelected method. The Menu Item selected is passed in to this method as the MenuItem parameter.

To react to the menu selection, compare the item.getItemId value to the Menu Item identifiers you used when populating the menu, and react accordingly, as shown in the following code:

public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item);

Find which menu item has been selected switch (item.getItemId()) {

Check for each known menu item case (MENU_ITEM):

[ ... Perform menu handler actions ... ] return true;


//Return false if you have not handled the menu item. return false;