Context Menu

The Android context menu is similar, in concept, to the menu revealed with a "right-click" on a PC. When a view is registered to a context menu, performing a "long-press" (press and hold for about two seconds) on the object will reveal a floating menu that provides functions relating to that item. Context menus can be registered to any View object, however, they are most often used for items in a ListView, which helpfully indicates the presence of the context menu by transforming the background color of the ListView item when pressed. (The items in the phone's contact list offer an example of this feature.)

Note: Context menu items do not support icons or shortcut keys.

To create a context menu, you must override the Activity's context menu callback methods: onCreateContextMenu() and onContextItemSelected() . Inside the onCreateContextMenu() callback method, you can add menu items using one of the add() methods, or by inflating a menu resource that was defined in XML. Then, register a ContextMenu for the View, with registerForContextMenu() .

For example, here is some code that can be used with the Notepad application to add a context menu for each note in the list:

In onCreateContextMenu() , we are given not only the ContextMenu to which we will add MenuItems, but also the View that was selected and a ContextMenuInfo object, which provides additional information about the object that was selected. In this example, nothing special is done in onCreateContextMenu() — just a couple items are added as usual. In the onContextItemSelected() callback, we request the AdapterContextMenuInfo from the MenuItem, which provides information about the currently selected item. All we need from this is the list ID for the selected item, so whether editing a note or deleting it, we find the ID with the field of the object. This ID is passed to the editNote( ) and deleteNote() methods to perfrom the respective action.

Now, to register this context menu for all the items in a ListView, we pass the entire ListView to the registerForContextMenu(View) method:


Remember, you can pass any View object to register a context menu. Here, getListView() returns the ListView object used in the Notepad application's ListActivity. As such, each item in the list is registered to this context menu.

0 0

Post a comment