Working with Context Menus

Users of desktop programs are no doubt familiar with context menus. In Windows applications, for example, you can access a context menu by right-clicking a UI element. Android supports the same idea of context menus through an action called a long click. A long click is a mouse click held down slightly longer than usual on any Android view.

On handheld devices such as cell phones, mouse clicks are implemented in a number of ways, depending on the navigation mechanism. If your phone has a wheel to move the cursor, a press of the wheel would serve as the mouse click. Or if the device has a touch pad, then a tap or a press would be equivalent to a mouse click. Or you might have a set of arrow buttons for movement and a selection button in the middle; clicking that button would be equivalent to clicking the mouse. Regardless of how a mouse click is implemented on your device, if you hold the mouse click a bit longer you will realize the long click.

A context menu differs structurally from the standard options menu that we've been discussing (see Figure 5-3). Context menus have some nuances that options menus don't have.

Figure 5-3 shows that a context menu is represented as a ContextMenu class in the Android menu architecture. Just like a Menu, a ContextMenu can contain a number of menu items. You will use the same set of Menu methods to add menu items to the context menu. The biggest difference between a Menu and a ContextMenu boils down to the ownership of the menu in question. An activity owns a regular options menu, whereas a view owns a context menu. This is to be expected because the long clicks that activate context menus apply to the view being clicked. So an activity can have only one options menu but many context menus. Because an activity can contain multiple views, and each view can have its own context menu, an activity can have as many context menus as there are views.

Although a context menu is owned by a view, the method to populate context menus resides in the Activity class. This method is called activity.onCreateContextMenu(), and its role resembles that of the activity.onCreateOptionsMenu() method. This callback method also carries with it the view for which the context menu items are to be populated.


Contains a single menu

- onCreateContextMenu() ■

-onCreateItemsSelectedQ ■

View extends

Register for context menu

Derived View

0 0

Post a comment