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

}<br />

menu.setHeaderTitle(“Context Menu”);<br />

menu.add(0, Menu.FIRST, Menu.NONE,<br />

“Item 1”).setIcon(R.drawable.menu_item);<br />

menu.add(0, Menu.FIRST+1, Menu.NONE, “Item 2”).setCheckable(true);<br />

menu.add(0, Menu.FIRST+2, Menu.NONE, “Item 3”).setShortcut(‘3’, ‘3’);<br />

SubMenu sub = menu.addSubMenu(“Submenu”);<br />

sub.add(“Submenu Item”);<br />

As shown in the preceding code, the ContextMenu class supports the same add method as the<br />

Menu class, so you can populate a Context Menu in the same way that you populate Activity<br />

menus — using the add method. This includes using the add method to add submenus to your<br />

Context Menus. Note that icons will never be displayed; however, you can specify the title and icon<br />

to display in the Context Menu’s header bar.<br />

<strong>Android</strong> also supports late runtime population of Context Menus via Intent Filters. This mechanism<br />

lets you populate a Context Menu by specifying the kind of data presented by the<br />

current View and asking other <strong>Android</strong> applications if they support any actions for it. The most<br />

common examples of this mechanism are the cut/copy/paste Menu Items available on Edit Text<br />

controls.<br />

Handling Context Menu Selections<br />

Context Menu Item selections are handled much the same as Activity Menu selections. You can<br />

attach an Intent or Menu Item Click Listener directly to each Menu Item or use the preferred technique<br />

of overriding the onContextItemSelected method on the Activity, as follows:<br />

@Override<br />

public boolean onContextItemSelected(MenuItem item) {<br />

super.onContextItemSelected(item);<br />

// TODO [ ... Handle Menu Item selection ... ]<br />

}<br />

return false;<br />

The onContextItemSelected event handler is triggered whenever a Context Menu Item is selected.<br />

Using Popup Menus<br />

An alternative to Context Menus, Popup Menus are displayed<br />

alongside a particular View instance, rather than above the entire<br />

Activity (see Figure 10-14). When targeting devices running<br />

<strong>Android</strong> 3.0 or above, it’s best practice to use Popup Menus rather<br />

than Context Menus.<br />

To assign a Popup Menu to a View, you must create a new Popup<br />

Menu, specifying the Activity Context and the View to which it<br />

should be anchored:<br />

final PopupMenu popupMenu = new PopupMenu(this,<br />

myView);<br />

FIGURE 10-14

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

Saved successfully!

Ooh no, something went wrong!