Defining an Activity Menu

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

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

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

You should always call through to the superclass implementation, as it automatically includes additional system menu options where appropriate.

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

V A group value to separate Menu Items for batch processing and ordering.

V A unique identifier for each Menu Item. For efficiency reasons, Menu Item selections are generally handled by the onOptionsltemSelected event handler, so this unique identifier is important for determining 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.

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

V The Menu Item display text, either as a character string or as a string resource. When you have finished populating the Menu return true.

Listing 4-26 shows how to add a single Menu Item to an Activity Menu.

LISTING 4-26: Adding a Menu Item Available for download on static final private int MENU_ITEM = Menu.FiRST; Wrox.com

©Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);

// Unique menu item identifier. Used for event handling.

int menultemid = MENU_ITEM;

// The order position of the item int menuitemOrder = Menu.NONE;

// Text to be displayed for this menu item.

int menuitemText = R.string.menu_item;

// Create the menu item and keep a reference to it. Menuitem menuitem = menu.add(groupid, menuitemid, menuitemOrder, menuitemText);

return true;

Like the Menu object, each Menuitem returned by 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 in to the Menu's finditem method.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment