Android basics 22: menu 01 -- Overview

Source: Internet
Author: User

1. Overview

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.

1.1 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. For more information about XML syntax and menu resource attributes, see menu resource section.

1.2 inflating a menu resource

In the code, use menuinflater. inflate () You can use inflate to convert an XML resource into an object in a program. for example, the following code uses the callback method oncreateoptionsmenu () to convert the game_menu.xml inflate file into a menu object and use it as the option menu of the activity:

@Override  public boolean onCreateOptionsMenu(Menu menu) {      MenuInflater inflater = getMenuInflater();      inflater.inflate(R.menu.game_menu, menu);      return true;  }  

Getmenuinflater () returns a menuinflater of the activity. With this object, you can call inflate () to convert menu resources to menu objects. in this example, the menu resource is inflate to the parameter menu of the oncreateoptionsmenu () method.

2. Create an option menu

The option menu should contain basic activity actions and required navigation entries (for example, a menu item set to open the program ). option menu items have two different options: one is the menu item button, and the other is the action bar (in Android 3.0 and later versions ).

Figure 1: option menu in the browser 2. Action bar in the email program, with two actions and an overflow menu

When running in Android 2.3 and earlier versions, the option menu appears at the bottom of the screen, as shown in figure 1. when you open the option menu, the icon menu is first displayed. It has six menu items. If you add more than six menu items, the system places the sixth menu item and the subsequent menu item in the overflow menu. You can open them through the "more" menu item.
In Android 3.0 and later versions, the option menu item is placed on the action bar. the action bar is located at the top of the activity, where the traditional title bar is located. by default, all menu items from the option menu are placed in the overflow menu. you can click the menu icon on the right of the action bar to open it. however, you can also put the menu item as "action items" directly on the action bar, as shown in figure 2.
When the system creates the option menu for the first time, it calls your activity method oncreateoptionsmenu (). override this method and create an instance for the input parameter menu. menu is created through an inflate menu resource, as follows:

@Override  public boolean onCreateOptionsMenu(Menu menu) {      MenuInflater inflater = getMenuInflater();      inflater.inflate(R.menu.game_menu, menu);      return true;  }  

You can also generate a menu in the Code and add a menu item using Add.
Note: In Android 2.3 and earlier versions, when you open the option menu for the first time, the system calls oncreateoptionsmenu () to create the option menu. However, in Android 3.0 and later versions, when an activity is created, the system creates an option menu to create an action bar.

2.1 respond to user actions

When you select a menu item (including the action item on the action bar), the system will call your activity method onoptionsitemselected (). this method will input the selected menu item in the parameter. you can call the getitemid () method to locate this menu item. This method returns the unique ID of the menu item (defined by the Android: Id attribute in the menu resource file or in the call Method Add () an integer ). you can use known menu items to match this ID and perform relevant actions, for example:

@Override  public boolean onOptionsItemSelected(MenuItem item) {      // Handle item selection      switch (item.getItemId()) {      case R.id.new_game:          newGame();          return true;      case R.id.help:          showHelp();          return true;      default:          return super.onOptionsItemSelected(item);      }  }  

In this example, getitemid () gets the ID of the selected menu item and compares it with all menu IDs in the resource file in the switch statement. If the menu item is successfully processed in the switch statement, true is returned to indicate that the selected menu item is processed. Otherwise, the default statement will pass the menu item to the parent class. Maybe the parent class will process this menu item (if you directly derive from activity, the parent class will return false, however, it is a good habit to pass unprocessed menu items to the parent class rather than directly returning false .)
In addition, Android 3.0 adds the ability to define the click behavior of menu items in the menu resource XML file, which is defined through the Android: onclick attribute. So you do not need to implement onoptionsitemselected (). using the Android: onclick attribute, you can specify a method to call when the menu item is selected. your activity must implement the method specified in the property Android: onclick. It accepts a menuitem parameter-The menu selected when the system calls this method is passed in from this parameter.
TIPS: If your program contains multiple activities and they provide the same option menu, consider creating an activity class that only implements oncreateoptionsmenu () and onoptionsitemselected, then, all the activities that provide the same menu options are derived from this class. in this way, you only need to manage a group of codes for the class's children and grandchildren.
If you want to add a menu item to the grandson activitie, you only need to override oncreateoptionsmenu (). call super. oncreateoptionsmenu (menu), so the original menu is created, and then you can use the menu method. add () to add a single dish. You can also override the parent class method to create other menu items.

3. Change menu items during running

Once the activity is created, the oncreateoptionsmenu () method will be called only once (as mentioned earlier ). the system will save and reuse this menu until your activity is destroyed. what if you want to change the menu after it is created? You must override onprepareoptionsmenu (). it will be passed to the instance of the menu you have created. this function is used when you want to delete, add, disable, or enable menu items based on the application status.
In Android 2.3 and earlier versions, the system calls onprepareoptionsmenu () each time the option menu is opened ().
In Android 3.0 and later versions, you must call the invalidateoptionsmenu () method before you want to update the menu, because the menu is always open. the system will call onprepareoptionsmenu (), so you can change the menu item.
Note: You should never change the option menu of the current view with focus. when you are in the touch mode (you have not used a trackball or direction key), views cannot get the focus, so you can never modify the menu items of the option menu based on the focus. if you want to provide context-sensitive Menu items for the view, use context menu.
If you are developing apps on Android 3.0 or later, read the action bar Development Guide.

4. Context Menu

A context menu is similar to a context menu on a PC. you should use the context menu to provide the action selection function for a part of the user interface. in Android, a context menu appears when you press an interface entry.
You can create a context menu for any view, but it is most commonly used in listview. every time you press a listview item and the listview registers a context menu, the context menu is displayed (this process is demonstrated in the Contact application ).
Register a listview
If your activity uses a listview and you want all list items to provide a context menu, you should pass the listview to the registerforcontextmenu () method. For example:
Registerforcontextmenu (getlistview ());
To make the view provide context menu, you must register the context menu for this view to the system. call the registerforcontextmenu () method and input the view to be displayed as the parameter. when the view is delayed, a context menu is displayed.
To define the context menu appearance and behavior, you need to override the context menu callback methods of your activity: oncreatecontextmenu () and oncontextitemselected ().
For example, the following is an oncreatecontextmenu () that uses the resource file context_menu.xml:

@Override  public void onCreateContextMenu(ContextMenu menu, View v,                                  ContextMenuInfo menuInfo) {    super.onCreateContextMenu(menu, v, menuInfo);    MenuInflater inflater = getMenuInflater();    inflater.inflate(R.menu.context_menu, menu);  }  

Menuinflater is used to extract a menu from a menu resource inflate. (You can also use add () to add menu items ). the callback function parameters include the View selected by the user and an ontextmenu. contextmenuinfo object, which provides more information about the selected view. you can use these parameters to determine which context menu should be created. in this example, all context menus of the activity are the same.
Then, when you select a menu item from the context menu, the system will call the oncontextitemselected () method. The following example shows how to process the selected menu item:

@Override  public boolean onContextItemSelected(MenuItem item) {    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();    switch (item.getItemId()) {    case R.id.edit:      editNote(info.id);      return true;    case R.id.delete:      deleteNote(info.id);      return true;    default:      return super.onContextItemSelected(item);    }  }  

These codes are basically the same as the example code in the option menu. getitemid () obtains the menu ID from the selected menu item, and uses the switch statement to match the corresponding processing of the menu ID. similar to the option menu example, the default statement calls the same method of the parent class to process menu items that are not processed by us.
In this example, the selected view entry is a listview entry. in order to execute the corresponding action on a selected view entry, the application needs to know the list ID of the view entry. to obtain the list ID, the program calls getmenuinfo () and returns an adapterview. adaptercontextmenuinfo object, which contains the list ID of the entry. the local methods editnote () and deletenote () accept this list ID for executing some operations.

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

5. Sub-menu

A sub-menu is a menu opened on a menu item of an existing menu. you can add sub-menus to any menu. when your program has many functions and can be organized by category, the sub-menu is the best choice. for example, the menu bar (file, edit, view, and so on) in a PC program .).
When creating a menu resource, you can add a <menu> element as a child of the <item> element to create a sub-menu. For example:

<?xml version="1.0" encoding="utf-8"?>  <menu xmlns:android="http://schemas.android.com/apk/res/android">      <item android:id="@+id/file"            android:icon="@drawable/file"            android:title="@string/file" >          <!-- "file" submenu -->          <menu>              <item android:id="@+id/create_new"                    android:title="@string/create_new" />              <item android:id="@+id/open"                    android:title="@string/open" />          </menu>      </item>  </menu>  

When you select a menu item from the sub-menu, the callback method selected for the response menu item of the parent menu will receive the event. for example, if the preceding menu is an option menu, the onoptionsitemselected () method will be called.
You can also use addsubmenu () to dynamically Add sub-menus to a menu. this method returns a New submenu object. You can use the add () method to add menu items to this submenu object.

References:

Android menu description 1: Overview
Android menu details 2: option menu
Android menu details 3: Context Menu
Android menu details 4: Sub menu

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.