20.08.2016 Views

Professional Android 4 Application Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating and Using Menus and Action Bar Action Items x 379<br />

are not displayed in the submenu, so it’s good practice to avoid assigning icons to submenu<br />

items.<br />

Because <strong>Android</strong> does not support nested submenus, you can’t add a submenu to a submenu<br />

(trying to do so will result in an exception), nor can you specify a submenu to be an action.<br />

Pressing the back button closes the floating window/menu.<br />

Creating a Menu<br />

To add a menu to an Activity, override its onCreateOptionsMenu handler. Prior to <strong>Android</strong> 3.0 this<br />

handler is triggered the first time an Activity’s menu is displayed; in <strong>Android</strong> 3.0 and above it’s triggered<br />

as part of creating the Action Bar each time the Activity is laid out.<br />

The onCreateOptionsMenu receives a Menu object as a parameter. You can store a reference to, and<br />

continue to use, the Menu reference elsewhere in your code until the next time onCreateOptions-<br />

Menu is called.<br />

You should always call through to the superclass implementation because it can add additional system<br />

menu options where appropriate.<br />

Use the add method on the Menu object to populate your menu. For each new Menu Item, you must<br />

specify the following:<br />

‰ A group value to separate Menu Items for batch processing and ordering.<br />

‰ A unique identifier for each Menu Item. For efficiency reasons, Menu Item selections<br />

normally are handled using the onOptionsItemSelected event handler, so this unique<br />

identifier makes it possible for you to determine which Menu Item was selected. It is conventional<br />

to declare each menu ID as a private static variable within the Activity class.<br />

You can use the Menu.FIRST static constant and simply increment that value for each subsequent<br />

item.<br />

‰ An order value that defines the order in which the Menu Items are displayed.<br />

‰ The Menu Item display text, either as a character string or as a string resource.<br />

When you have finished populating the Menu, return true to indicate that you have handled the<br />

Menu creation.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!