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.

382 x CHAPTER 10 EXPANDING THE USER EXPERIENCE<br />

‰ Icons — Icons are displayed only in the icon menu or as an action; they are not visible<br />

in the extended menu or submenus. You can specify any Drawable resource as a menu<br />

icon.<br />

menuItem.setIcon(R.drawable.menu_item_icon);<br />

‰ Menu item click listener — An event handler that will execute when the Menu Item is<br />

selected. For efficiency, the use of such an event handler is discouraged; instead, Menu Item<br />

selections should be handled by the onOptionsItemSelected handler, as shown in the<br />

“Handling Menu Selections” section later in this chapter.<br />

menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {<br />

public boolean onMenuItemClick(MenuItem _menuItem) {<br />

[ ... execute click handling, return true if handled ... ]<br />

return true;<br />

}<br />

});<br />

‰ Intents — An Intent assigned to a Menu Item is triggered when a Menu Item click isn’t<br />

handled by a MenuItemClickListener or the Activity’s onOptionsItemSelected handler.<br />

When the Intent is triggered, <strong>Android</strong> will execute startActivity, passing in the specified<br />

Intent.<br />

menuItem.setIntent(new Intent(this, MyOtherActivity.class));<br />

Adding Action Views and Action Providers<br />

The introduction of actions and the Action Bar in <strong>Android</strong> 3.0 (API level 11) made it possible to add<br />

richer interaction modes to the menu system. In particular, it’s now possible to add interactive Views<br />

to your Action Bar actions in the form of action Views and Action Providers.<br />

You can replace the icon/text used to represent an action with any View or layout using the Menu<br />

Item’s setActionView method, passing in either a View instance or a layout resource, as shown in<br />

Listing 10-13.<br />

LISTING 10-13: Adding an action View<br />

menuItem.setActionView(R.layout.my_action_view)<br />

.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM|<br />

MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);<br />

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

Once added, the action View will be displayed whenever the associated Menu Item is displayed as<br />

an action in the Action Bar, but will never be displayed if the Menu Item is relegated to the overflow<br />

menu.<br />

A better alternative, introduced in <strong>Android</strong> 4.0 (API level 14), is to add the MenuItem.SHOW_AS_<br />

ACTION_COLLAPSE_ACTION_VIEW flag. When this flag is set, the Menu Item will be represented using

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

Saved successfully!

Ooh no, something went wrong!