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.

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

Using Context Menus and Popup Menus<br />

Context Menus are contextualized by the currently focused View and are triggered when a user<br />

long-presses the trackball, middle D-pad button, or a View (typically for approximately 3 seconds).<br />

A Context Menu is displayed as a floating window above your Activity.<br />

<strong>Android</strong> 3.0 (API level 11) introduced the PopupMenu class, a lighter-weight alternative to the<br />

ContextMenu that anchors itself to a specific View.<br />

You define and populate Context Menus and Popup Menus as you define and populate Activity<br />

Menus. There are two options available for creating Context Menus for a particular View.<br />

Creating Context Menus<br />

One option is to create a generic ContextMenu object for a View class by overriding a View’s<br />

onCreateContextMenu handler, as shown here:<br />

@Override<br />

public void onCreateContextMenu(ContextMenu menu) {<br />

super.onCreateContextMenu(menu);<br />

menu.add(“ContextMenuItem1”);<br />

}<br />

The Context Menu created here will be available within any Activity that includes this View class.<br />

The more common alternative is to create Activity-specific Context Menus by overriding the<br />

Activity’s onCreateContextMenu method, and registering the Views that should use it using the<br />

registerForContextMenu method, as shown in Listing 10-19.<br />

LISTING 10-19: Assigning a Context Menu to a View<br />

@Override<br />

public void onCreate(Bundle savedInstanceState) {<br />

super.onCreate(savedInstanceState);<br />

EditText view = new EditText(this);<br />

setContentView(view);<br />

}<br />

registerForContextMenu(view);<br />

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

Once a View has been registered, the onCreateContextMenu handler will be triggered the first time<br />

a Context Menu is displayed for that View.<br />

To populate the Context Menu parameter with the appropriate Menu Items, override onCreate<br />

ContextMenu and check which View has triggered the menu creation.<br />

@Override<br />

public void onCreateContextMenu(ContextMenu menu, View v,<br />

ContextMenu.ContextMenuInfo menuInfo) {<br />

super.onCreateContextMenu(menu, v, menuInfo);

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

Saved successfully!

Ooh no, something went wrong!