Recipe 2.15 Displaying Context and Options Menus

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
ContextAndOptionsMenu.zip

Menus are useful for displaying additional options that are not directly visible on the main UI of an application. You can add two main types of menus in Android:

  • Options menu — Displays information related to the current activity. In Android, you activate the options menu by pressing the MENU key. The menu items displayed vary according to the current activity that is running.
  • Context menu — Displays information related to a particular view on an activity. In Android, to activate a context menu you tap and hold it.

This recipe shows how to create the options and context menus for your Android application.

Solution

To create either an options menu or a context menu, populate the activity_main.xml file in the res/menu folder as follows:

<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu1" android:icon="@drawable/ic_action_search" android:orderInCategory="100" android:showAsAction="always" android:title="Item 1"/> <item android:id="@+id/menu2" android:orderInCategory="100" android:showAsAction="ifRoom" android:title="Item 2"> <menu> <item android:id="@+id/menu21" android:title="Item 2.1"/> <item android:id="@+id/menu22" android:title="Item 2.2"/> <item android:id="@+id/menu23" android:title="Item 2.3"/> </menu> </item> <item android:id="@+id/menu3" android:orderInCategory="100" ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.