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 381<br />

LISTING 10-12: Making a Menu Item an action<br />

menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM |<br />

MenuItem.SHOW_AS_ACTION_WITH_TEXT);<br />

code snippet PA4AD_Ch10_ActionBar/src/ActionBarActivity.java<br />

Menu Item Options<br />

<strong>Android</strong> supports most of the traditional Menu Item options you’re probably familiar with, including<br />

icons, shortcuts, check boxes, and radio buttons, as listed here:<br />

‰ Check boxes — Check boxes on Menu Items are visible in the overflow and expanded menus,<br />

as well as within submenus. To set a Menu Item as a check box, use the setCheckable<br />

method. The state of that check box is controlled via setChecked.<br />

// Create a new check box item.<br />

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

‰ Radio buttons — A radio button group is a group of items displaying circular buttons, in<br />

which only one item can be selected at any given time. Checking one of these items will automatically<br />

uncheck any checked item in the same group.<br />

To create a radio button group, assign the same group identifier to each item and then call<br />

Menu.setGroupCheckable, passing in that group identifier and setting the exclusive parameter<br />

to true:<br />

// Create a radio button group.<br />

menu.add(RB_GROUP, RADIOBUTTON_1, Menu.NONE, “Radiobutton 1”);<br />

menu.add(RB_GROUP, RADIOBUTTON_2, Menu.NONE, “Radiobutton 2”);<br />

menu.add(RB_GROUP, RADIOBUTTON_3, Menu.NONE,<br />

“Radiobutton 3”).setChecked(true);<br />

menu.setGroupCheckable(RB_GROUP, true, true);<br />

‰ Shortcut keys — You can specify a keyboard shortcut for a Menu Item by using the<br />

setShortcut method. Each call to setShortcut requires two shortcut keys — one for<br />

use with the numeric keypad and another to support a full keyboard. Neither key is<br />

case-sensitive.<br />

// Add a shortcut to this Menu Item, ‘0’ if using the numeric keypad<br />

// or ‘b’ if using the full keyboard.<br />

menuItem.setShortcut(‘0’, ‘b’);<br />

‰ Condensed titles — The setTitleCondensed method lets you specify text to be displayed<br />

only in the icon menu or as Action Bar actions. The normal title will only be used when the<br />

Menu Item is displayed in the overflow or extended menu.<br />

menuItem.setTitleCondensed(“Short Title”);

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

Saved successfully!

Ooh no, something went wrong!