Menus in Context

By and large, context menus use the same guts as option menus - the contextMenu class extends the regular Menu class, offering only the means to set a "header" or caption for the popup menu via setHeader(). The two main differences are how you populate the menu and how you are informed of menu choices.

Since context menus are per-widget, rather than per-activity, there is no callback in the Activity to populate the context menu the way there is onCreateOptionsMenu() to populate the options menu. Instead, each widget itself is told when to populate the context menu. To save you the total headache of subclassing a bunch of widgets just to set up your context menus, though, Android offers a setOnPopulateContextMenuListener() method on all widgets. This takes an instance of the OnPopulateContextMenuListener callback interface. Your implementation of that interface - specifically, your implementation of onPopulateContextMenu () - is where you set up the contents of the context menu.

The onPopulateContextMenu() method gets the ContextMenu itself, the View the context menu is associated with, and an opaque Object representing "extra information" about the menu being built. If the context menu is for a selection widget that inherits from AdapterView, this object is supposed to be an instance of ContextMenulnfo, which tells you which item in the list the user did the tap-and-hold over, in case you want to customize the context menu based on that information. For example, you could toggle a checkable menu choice based upon the current state of the item. Note that you only get this "extra information" when the menu is built, not when a choice is made.

It is also important to note that onPopulateContextMenu() gets called for each time the context menu is requested. Unlike the options menu (which is only built once per activity), context menus are discarded once they are used or dismissed. Hence, you do not want to hold onto the supplied contextMenu object; just rely on getting the chance to rebuild the menu to suit your activity's needs on an on-demand basis based on user actions.

To find out when a context menu choice was chosen, implement onContextltemSelected() on the activity. Note that you only get the Menu.Item instance that was chosen in this callback. As a result, if your activity has two or more context menus, you may want to ensure they have unique menu item identifiers for all their choices, so you can tell them apart in this callback. Otherwise, this callback behaves the same as onOptionsitemSelected() as is described above.

Self Publishing

Self Publishing

Have you always wanted to write your own book and get it published? Discover How to Write, Print Sell Your Own Book! Have you always wanted to write your own book and get it published? If you have written a book or even if you have a yen to be a writer, you are probably already aware of the competition in the writing field.

Get My Free Ebook


Post a comment