Android Tutorial

(avery) #1
Android Tutorial 201

Enabling the ContextMenu

The ContextMenu is a subtype of Menu that you can configure to
display when a long press is performed on a View. As the name
implies, the ContextMenu provides for contextual menus to display
to the user for performing additional actions on selected items.

ContextMenu objects are slightly more complex than OptionsMenu
objects. You need to implement the onCreateContextMenu()
method of your Activity for one to display. However, before that is
called, you must call the registerForContextMenu() method and
pass in the View for which you want to have a context menu. This
means each View on your screen can have a different context
menu, which is appropriate as the menus are designed to be highly
contextual.

Here we have an example of a Chronometer timer, which responds
to a long click with a context menu:

registerForContextMenu(timer);


After the call to the registerForContextMenu() method has been
executed, the user can then long click on the View to open the
context menu. Each time this happens, your Activity gets a call to
the onCreateContextMenu() method, and your code creates the
menu each time the user performs the long click.

The following is an example of a context menu for the Chronometer
control, as previously used:

public void onCreateContextMenu(
ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);

Free download pdf