Menus are an important part of Activity. It provides a great way for user operations. Android provides a simple framework to add standard menus to programs.
There are three types of menus:
Option menu
The main set of menu items of an activity. When you press the MENU button (on the hardware), it will appear. If your program runs on Android 3.0 or later, you can directly put the menu item as "action items" on the Actiion Bar to provide quick selection.
Pop-up menu
A floating menu item is displayed when you hold down a View that has registered a pop-up menu.
Sub-menu
It is also a floating menu item that appears when you click a menu item that contains embedded menus.
This document describes how to create various types of menus, how to use XML to define menu content, and how to define callback functions in the Activity to respond to menu items.
Create a menu resource
You need to define a menu in an XML menu resource instead of in the code, and then inflate the menu resource in the code. Using menu resources to define menus is a good practice, because this can separate the interface from the code. In addition, it is easier to design your menu in XML.
To create a menu resource, first create an XML file under res/menu/of your project, and then create a menu with the following elements:
<Menu>
Define a menu, which is the container of the menu item. <Menu> must be the root node of the file. It can contain one or more <item> and <group> elements.
<Item>
Create a menu item. You can continue to include the <menu> element in the menu item. In this case, it has a sub menu.
<Group>
An optional, invisible container that contains <item> elements. It allows you to classify menu items so that similar menu items share some attributes, such as activity status and visible status. See the Menu groups section.
The following is an example of a menu named game_menu.xml:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Menu xmlns: android = "http://schemas.android.com/apk/res/android">
<Item android: id = "@ + id/new_game"
Android: icon = "@ drawable/ic_new_game"
Android: title = "@ string/new_game"/>
<Item android: id = "@ + id/help"
Android: icon = "@ drawable/ic_help"
Android: title = "@ string/help"/>
</Menu>
In this example, two menu items are defined, each of which includes the following attributes:
Android: id
A resource ID indicates a menu item. When you select a menu item, the program can use this ID to identify this menu item.
Android: icon
Reference A drawable icon for the menu item.
Android: title
Reference a string used for the title of a menu item.
There are also many attributes that can be used in <item>, including the attributes that specify how menu items are displayed in Action Bar.