Книга: Beginning Android

Menus in Context

Menus in Context

By and large, context menus use the same guts as option menus. The two main differences are how you populate the menu and how you are informed of menu choices.

First you need to indicate which widget(s) on your activity have context menus. To do this, call registerForContextMenu() from your activity, supplying the View that is the widget in need of a context menu.

Next you need to implement onCreateContextMenu(), which, among other things, is passed the View you supplied in registerForContextMenu(). You can use that to determine which menu to build, assuming your activity has more than one.

The onCreateContextMenu() method gets the ContextMenu itself, the View the context menu is associated with, and a ContextMenu.ContextMenuInfo, 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 on the current state of the item.

It is also important to note that onCreateContextMenu() gets called each time the context menu is requested. Unlike the options menu (which is built only 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 demand based on user actions.

To find out when a context-menu choice was selected, implement onContextItemSelected() on the activity. Note that you get only the MenuItem 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. Also, you can call getMenuInfo() on the MenuItem to get the ContextMenu.ContextMenuInfo you received in onCreateContextMenu(). Otherwise, this callback behaves the same as onOptionsItemSelected(), described in the previous section.

Оглавление книги


Генерация: 0.719. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз