Android provides the user with the ability to display a special type of menu that contains a set of items that pertains to the entire app, instead of the current activity.
Adding an options menu to our app is very simple, and only two things are required: a menu structure and code to connect the menu with the activity. In order to use a menu layout file, a resource file needs to be added:
Options.xml
, in the menu
folder under the Resources
folder.refresh
, settings
, and about
.<?xml version="1.0" encoding="utf-8" ?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/action_refresh" android:icon="@drawable/ic_action_refresh" android:title="@string/action_refresh" /> <item android:id="@+id/action_settings" android:title="@string/action_settings" /> <item android:id="@+id/action_about" android:title="@string/action_about"/> </menu>
OnCreateOptionsMenu()
method and inflate the resource:public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.Options, menu); return true; }
OnOptionsItemSelected()
method:public override bool OnOptionsItemSelected(IMenuItem item) { if (item.ItemId == Resource.Id.action_refresh) { // do something here... return true; // we handled the event } return base.OnOptionsItemSelected(item); }
Menus, especially the options menu, are both simple and important to Android apps. The Options menu contains items that are relevant to the current activity. They are important, but they are often not commonly used and so don't have a dedicated space in the layout.
As with traditional layout files, using resource files for menus allows greater flexibility for the many screen configurations as well as for simplifying customizations to menus.
Each menu item contains a unique ID, which allows the system to recognize the item when the user selects it, and a title, which is used to present the item to the user. There are also additional properties, the most commonly used of these being the icon. When using action bars, this icon is used to display an image alongside, or in place of, the title.
The MenuInflater
instance creates the menu structure from the resource file and inflates it into the IMenu
instance. All the menu items in the resource will be added as children to the menu.
When we handle the menu item selections, the menu item that was selected is passed into the OnOptionsItemSelected()
method. If the event was handled, true
should be returned; otherwise, the system will keep on processing the event.
We can use any of the properties on the menu item, but one of the more commonly used ones is ItemId
, which contains the ID that was used in the resource file. This ID can be used to determine which item was selected.