`

【翻译】(15)菜单(2012-02-03废弃)

 
阅读更多

【翻译】(15)菜单(2012-02-03废弃)

 

see

http://developer.android.com/guide/topics/ui/menus.html

 

原文见

http://developer.android.com/guide/topics/ui/menus.html

 

-------------------------------

 

Menus

 

菜单

 

-------------------------------

 

In this document

 

本文目录

 

* Creating a Menu Resource 创建菜单资源

* Inflating a Menu Resource 解压菜单资源

* Creating an Options Menu 创建选项菜单

* Changing menu items at runtime 运行期改变菜单条目

* Creating a Context Menu 创建上下文菜单

* Creating a Submenu 创建子菜单

* Other Menu Features 其它菜单特性

* Menu groups 菜单组

* Checkable menu items 可勾选的菜单条目

* Shortcut keys 快捷键

* Dynamically adding menu intents 动态添加菜单意图

 

Key classes 

 

关键类

 

Menu

MenuItem

ContextMenu

SubMenu

 

See also

 

另见

 

Action Bar

Menu Resource

 

-------------------------------

 

Menus are an important part of an activity's user interface, which provide users a familiar way to perform actions. Android offers a simple framework for you to add standard menus to your application.

 

菜单是活动的用户界面的重要部分,向用户提供一种熟悉方式来执行动作。Android为你提供一个简单框架添加标准菜单到你的应用程序。

 

There are three types of application menus:

 

有三类应用程序菜单:

 

* Options Menu

 

* 选项菜单

 

The primary collection of menu items for an activity, which appears when the user touches the MENU button. When your application is running on Android 3.0 or later, you can provide quick access to select menu items by placing them directly in the Action Bar, as "action items."

 

活动菜单条目的主要集合,当用户触碰MENU键时出现。当你的应用程序运行在Android 3.0或以后时,你可以通过直接放置菜单在动作栏来提供选择菜单条目的快速访问方式,即“动作条目”。

 

* Context Menu

 

* 上下文菜单

 

A floating list of menu items that appears when the user touches and holds a view that's registered to provide a context menu.

 

一种浮动的菜单条目列表,当用户触碰和按住一个被注册以提供上下文残带的视图时出现。

 

* Submenu

 

* 子菜单

 

A floating list of menu items that appears when the user touches a menu item that contains a nested menu.

 

一种浮动的菜单条目列表,当用户触碰一个包含内嵌菜单的菜单条目时出现。

 

This document shows you how to create each type of menu, using XML to define the content of the menu and callback methods in your activity to respond when the user selects an item.

 

本文向你展示如何创建各类菜单,使用XML定义菜单内容和你的活动中的回调方法,当用户选择一个条目时作成响应。

 

-------------------------------

 

Creating a Menu Resource

 

创建菜单资源

 

Instead of instantiating a Menu in your application code, you should define a menu and all its items in an XML menu resource, then inflate the menu resource (load it as a programmable object) in your application code. Using a menu resource to define your menu is a good practice because it separates the content for the menu from your application code. It's also easier to visualize the structure and content of a menu in XML.

 

你不应该在你的应用程序代码中实例化一个Menu,而应该在一个XML菜单资源中定义菜单和它的所有条目,然后在你的应用程序代码中解压菜单资源(加载它作为一个可编程对象)。使用菜单资源定义你的菜单是一条最佳实践,因为它从你的应用程序代码中分离菜单内容。它还更简单地用XML可视化菜单的结构和内容。

 

To create a menu resource, create an XML file inside your project's res/menu/ directory and build the menu with the following elements:

 

为了创建菜单资源,请在你的工程的res/menu/目录里创建一个XML文件并用以下元素构建菜单:

 

* <menu>

 

Defines a Menu, which is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and <group> elements.

 

定义一个菜单,它是菜单条目的容器。<menu>元素必须是文件的根节点,并且可以持有一个或多个<item>和<group>元素。

 

* <item>

 

Creates a MenuItem, which represents a single item in a menu. This element may contain a nested <menu> element in order to create a submenu.

 

创建一个MenuItem,它代表菜单中一个单一条目。这个元素可以包含一个内嵌的<menu>元素以创建一个子菜单。

 

* <group>

 

An optional, invisible container for <item> elements. It allows you to categorize menu items so they share properties such as active state and visibility. See the section about Menu groups.

 

<item>元素的可选的、不可见容器。它允许你分类菜单条目使它们共享属性诸如激活状态和可见性。请参见关于菜单组的章节。

 

Here's an example menu named game_menu.xml:

 

这里有一个示例菜单,名为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>

 

-------------------------------

 

This example defines a menu with two items. Each item includes the attributes:

 

这个示例定义一个带有两个条目的菜单。每个条目包含以下属性:

 

* android:id

 

A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it.

 

一个对于条目来说是唯一的资源ID,它允许应用程序在用户选择条目时可以识别它。

 

* android:icon

 

A reference to a drawable to use as the item's icon.

 

一个可画对象的引用,用作条目的图标。

 

* android:title

 

A reference to a string to use as the item's title.

 

一个字符串的引用,用作条目的标题。

 

There are many more attributes you can include in an <item>, including some that specify how the item may appear in the Action Bar. For more information about the XML syntax and attributes for a menu resource, see the Menu Resource reference.

 

你还可以在<itme>内包含大量更多的属性,包括一些属性指定条目可以如何显示在动作栏中。想获取关于菜单资源的XML语法和属性的更多信息,请参见菜单资源参考手册。

 

-------------------------------

 

Inflating a Menu Resource

 

解压菜单资源

 

From your application code, you can inflate a menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate(). For example, the following code inflates the game_menu.xml file defined above, during the onCreateOptionsMenu() callback method, to use the menu as the activity's Options Menu:

 

从你的应用程序代码中,你可以使用MenuInflater.inflate()解压菜单资源(转换XML资源为可编程对象)。例如,以下代码在onCreateOptionsMenu()回调方法期间解压上面定义的game_menu.xml文件,以使用菜单作为活动的选项菜单:

 

-------------------------------

 

@Override

public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();

    inflater.inflate(R.menu.game_menu, menu);

    return true;

}

 

-------------------------------

 

The getMenuInflater() method returns a MenuInflater for the activity. With this object, you can call inflate(), which inflates a menu resource into a Menu object. In this example, the menu resource defined by game_menu.xml is inflated into the Menu that was passed into onCreateOptionsMenu(). (This callback method for the Options Menu is discussed more in the next section.)

 

getMenuInflater()方法返回一个MenuInflater给活动使用。使用此对象,你可以调用inflate(),它解压一个菜单资源为一个Menu对象。在这个示例中,由game_menu.xml定义的菜单资源被解压进Menu对象,传递进onCreateOptionsMenu()。(这个选项菜单的回调方法在下一个章节中会进行更详细的讨论)。

 

-------------------------------

 

Creating an Options Menu

 

创建选项菜单

 

(图1略)

 

Figure 1. Screenshot of the Options Menu in the Browser.

 

图1. 浏览器中选项菜单的截屏。

 

The Options Menu is where you should include basic activity actions and necessary navigation items (for example, a button to open the application settings). Items in the Options Menu are accessible in two distinct ways: the MENU button or in the Action Bar (on devices running Android 3.0 or higher).

 

你应该在选项菜单中包含基本活动动作和必须导航条目(例如,一个打开应用程序设置的按钮)。选项菜单中的条目以两种不同方式访问:MENU按钮或在动作栏中(运行在Android 3.0或以上的设备)。

 

When running on a device with Android 2.3 and lower, the Options Menu appears at the bottom of the screen, as shown in figure 1. When opened, the first visible portion of the Options Menu is the icon menu. It holds the first six menu items. If you add more than six items to the Options Menu, Android places the sixth item and those after it into the overflow menu, which the user can open by touching the "More" menu item.

 

当运行在带有Android 2.3或更低的设备上时,选项菜单出现在屏幕底部,正如图1所示。当打开时,选项菜单第一个可见部分是图标菜单。它持有最先的六个菜单条目。如果你添加多于六个条目到选项菜单,Android只放置六个条目(注:包括More在内?),而后面那些都放进一个溢出菜单,让用户可以通过触碰“More(更多)”菜单条目来打开。

 

On Android 3.0 and higher, items from the Options Menu is placed in the Action Bar, which appears at the top of the activity in place of the traditional title bar. By default all items from the Options Menu are placed in the overflow menu, which the user can open by touching the menu icon on the right side of the Action Bar. However, you can place select menu items directly in the Action Bar as "action items," for instant access, as shown in figure 2.

 

在Android 3.0和更高版本,选项菜单的条目被放置进动作栏,它出现在活动的顶部覆盖传统的标题栏的位置。默认选项菜单的所有条目放进溢出菜单,让用户可以通过触碰动作栏右侧的菜单图标来获取。然而,你可以直接把选择菜单条目放进动作栏作为“动作条目”,以提供即时访问方式,正如图2所示。(注:题外话,Android 3.0是完全软键盘的,所有操作都是触碰的。桌面状态下右上角的两个按钮分别是应用列表和MENU键。进入应用后左下角会出现四个按钮,分别对应后退键、HOME键、最近打开列表、MENU键,第四个按钮有时不出现。另外,有些应用的右上角会出现一些按钮和一个可打开下拉菜单的四条平行线图标,点击左上角的应用图标有时可执行后退操作)

 

When the Android system creates the Options Menu for the first time, it calls your activity's onCreateOptionsMenu() method. Override this method in your activity and populate the Menu that is passed into the method, Menu by inflating a menu resource as described above in Inflating a Menu Resource. For example:

 

当Android系统第一次创建选项菜单时,它对应你的活动的onCreateOptionsMenu()方法。在你的活动中覆盖此方法,通过解压前面关于解压菜单资源章节中所描述的菜单资源,把菜单注入到传递给此方法的Menu参数。例如:

 

-------------------------------

 

@Override

public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();

    inflater.inflate(R.menu.game_menu, menu);

    return true;

}

 

-------------------------------

 

(图2略)

 

Figure 2. Action bar from the Honeycomb Gallery app, including navigation tabs and a camera action item (plus the overflow menu button).

 

图2. Honeycomb(注:Android 3.0的代号为“蜂巢”)画廊应用(注:一个官方示例程序)动作栏,包含导航标签页和一个照相机动作条目(以及溢出菜单按钮)。

 

You can also populate the menu in code, using add() to add items to the Menu.

 

你还可以用代码生成菜单,使用add()添加条目到Menu对象中。

 

-------------------------------

 

Note: On Android 2.3 and lower, the system calls onCreateOptionsMenu() to create the Options Menu when the user opens it for the first time, but on Android 3.0 and greater, the system creates it as soon as the activity is created, in order to populate the Action Bar.

 

注意:在Android 2.3和更低版本,当用户首次打开选项菜单时系统调用onCreateOptionsMenu()创建它,但在Android 3.0和更高版本,系统在活动被创建时就创建它,以生成动作栏。

 

-------------------------------

 

Responding to user action

 

响应用户动作

 

When the user selects a menu item from the Options Menu (including action items in the Action Bar), the system calls your activity's onOptionsItemSelected() method. This method passes the MenuItem that the user selected. You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). You can match this ID against known menu items and perform the appropriate action. For example:

 

当用户从选项菜单中选择一个菜单条目时(包括动作栏中的动作条目),系统会调用你的活动的onOptionsItemSelected()方法。此方法传递用户选中的MenuItem。你可以通过调用getItemId()标识菜单条目,它返回菜单条目的唯一ID(由菜单资源中的android:id属性定义或add()方法中所给的整数)。你可以针对已知菜单条目匹配此ID并执行合适的动作。例如:

 

-------------------------------

 

@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() queries the ID for the selected menu item and the switch statement compares the ID against the resource IDs that were assigned to menu items in the XML resource. When a switch case successfully handles the menu item, it returns true to indicate that the item selection was handled. Otherwise, the default statement passes the menu item to the super class, in case it can handle the item selected. (If you've directly extended the Activity class, then the super class returns false, but it's a good practice to pass unhandled menu items to the super class instead of directly returning false.)

 

在这个示例中,getItemId()查询选中菜单条目的ID并用switch语句比较该ID和在XML资源中赋给菜单条目的资源ID。当一个switch的case成功处理菜单条目时,它返回true以指出选中的条目已经被处理了。否则,default语句把菜单条目传递给超类,假设它可以处理选中的条目。(如果你是直接扩展Activity类的,那么超类返回false,但最佳实践是传递未处理的菜单条目给超类而非直接返回false。)

 

Additionally, Android 3.0 adds the ability for you to define the on-click behavior for a menu item in the menu resource XML, using the android:onClick attribute. So you don't need to implement onOptionsItemSelected(). Using the android:onClick attribute, you can specify a method to call when the user selects the menu item. Your activity must then implement the method specified in the android:onClick attribute so that it accepts a single MenuItem parameter—when the system calls this method, it passes the menu item selected.

 

另外,Android 3.0添加功能,让你可以使用android:onClick属性定义菜单资源XML内菜单条目的点击行为。所以你不需要实现onOptionsItemSelected()。使用android:onClick属性,你可以指定在用户选中菜单条目时要调用的方法。然后活动必须实现在android:onClick属性中指定的方法,让其接受单一MenuItem参数——当系统调用此方法时,它传递选中的菜单条目。

 

-------------------------------

 

Tip: If your application contains multiple activities and some of them provide the same Options Menu, consider creating an activity that implements nothing except the onCreateOptionsMenu() and onOptionsItemSelected() methods. Then extend this class for each activity that should share the same Options Menu. This way, you have to manage only one set of code for handling menu actions and each descendant class inherits the menu behaviors.

 

提示:如果你的应用程序包含多个活动,而它们中的一些提供相同的选项菜单,请考虑创建一个活动,它什么都不实现,除了onCreateOptionsMenu()和onOptionsItemSelected()方法。然后为每个应该共享相同选项菜单的活动扩展此类。使用此方法,你必须管理唯一的代码集合以处理菜单行为,而每个后代类继承该菜单行为。

 

If you want to add menu items to one of your descendant activities, override onCreateOptionsMenu() in that activity. Call super.onCreateOptionsMenu(menu) so the original menu items are created, then add new menu items with menu.add(). You can also override the super class's behavior for individual menu items.

 

如果你希望添加菜单条目到你的其中一个后代活动,请在活动中覆盖onCreateOptionsMenu()。调用super.onCreateOptionsMenu(menu)使原来的菜单条目被创建,然后用menu.add()添加新的菜单条目。你还可以覆盖单独菜单条目的超类行为。

 

-------------------------------

 

Changing menu items at runtime

 

运行期改变菜单条目

 

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.

 

一旦活动被创建,onCreateOptionsMenu()方法被调用仅一次,正如上面描述的那样。系统保留和重用你在此方法中定义的菜单,直至你的活动被销毁。如果你希望在它首次被创建后的任意时刻改变选项菜单,你必须覆盖onPrepareOptionsMenu()方法。它把Menu对象传给你,如果它现在存在的话。这是有用的,如果你想移除、添加、屏蔽或使能菜单条目,依赖于你的应用程序的当前状态。

 

On Android 2.3 and lower, the system calls onPrepareOptionsMenu() each time the user opens the Options Menu.

 

在Android 2.3和更低的版本,每当用户打开选项菜单时,系统调用onPrepareOptionsMenu()

 

On Android 3.0 and higher, you must call invalidateOptionsMenu() when you want to update the menu, because the menu is always open. The system will then call onPrepareOptionsMenu() so you can update the menu items.

 

在Android 3.0和更高版本,你必须在你希望更新菜单时调用invalidateOptionsMenu(),因为菜单总是被代开。然后系统将调用onPrepareOptionsMenu()使你可以更新菜单条目。

 

-------------------------------

 

Note: You should never change items in the Options Menu based on the View currently in focus. When in touch mode (when the user is not using a trackball or d-pad), views cannot take focus, so you should never use focus as the basis for modifying items in the Options Menu. If you want to provide menu items that are context-sensitive to a View, use a Context Menu.

 

注意:你应该从不更新基于当前获取焦点的视图中的选项菜单内的条目。当在触碰模式下(当用户不在使用轨迹球或d-pad)(注:d-pad是directional pad方向键盘的缩写),视图不能获取焦点,所以你应该从不使用焦点作为修改选项菜单条目的基础。如果你希望提供菜单条目对于View是上下文敏感,请使用上下文菜单。

 

-------------------------------

 

If you're developing for Android 3.0 or higher, be sure to also read the Action Bar developer guide.

 

如果你正在开发Android 3.0或更高版本,请确保还阅读过动作栏开发者指引。

 

-------------------------------

 

Creating a Context Menu

 

创建上下文菜单

 

A context menu is conceptually similar to the menu displayed when the user performs a "right-click" on a PC. You should use a context menu to provide the user access to actions that pertain to a specific item in the user interface. On Android, a context menu is displayed when the user performs a "long press" (press and hold) on an item.

 

上下文菜单概念上类似于用户在个人电脑上执行“右键点击”时显示的菜单。你应该使用上下文菜单向用户提供关于用户界面中特定条目的动作的访问。在Android上,一个上下文菜单在用户在一个条目上执行“长按”(按下并按住)时显示。

 

You can create a context menu for any View, though context menus are most often used for items in a ListView. When the user performs a long-press on an item in a ListView and the list is registered to provide a context menu, the list item signals to the user that a context menu is available by animating its background color—it transitions from orange to white before opening the context menu. (The Contacts application demonstrates this feature.)

 

你可以创建任意View的上下文菜单,虽然上下文菜单最常用于ListView的条目。当用户在ListView中的条目上执行长按动作,而该列表被注册以提供上下文菜单时,列表条目通过动画它的背景颜色来通知用户上下文菜单有效——它在打开上下文菜单之前从橙色转换为白色。(联系人应用程序演示此特性)

 

-------------------------------

 

Register a ListView

 

注册一个ListView

 

If your activity uses a ListView and you want all list items to provide a context menu, register all items for a context menu by passing the ListView to registerForContextMenu(). For example, if you're using a ListActivity, register all list items like this:

 

如果你的活动使用一个ListView而你希望所有列表条目提供一个上下文菜单,请通过传递那个ListView给registerForContextMenu(),注册所有条目到上下文菜单。例如,如果你正在使用一个ListActivity,那么像这样注册所有列表条目:

 

registerForContextMenu(getListView());

 

-------------------------------

 

In order for a View to provide a context menu, you must "register" the view for a context menu. Call registerForContextMenu() and pass it the View you want to give a context menu. When this View then receives a long-press, it displays a context menu.

 

为了为一个View提供上下文菜单,你必须“注册”视图到一个上下文菜单。调用registerForContextMenu()并传递给它你想传给上下文菜单的View。然后当这个View接收一个长按时,它显示一个上下文菜单。

 

To define the context menu's appearance and behavior, override your activity's context menu callback methods, onCreateContextMenu() and onContextItemSelected().

 

为了定义上下文菜单的外观和行为,请覆盖你的活动的上下文菜单回调方法,onCreateContextMenu()和onContextItemSelected()。

 

For example, here's an onCreateContextMenu() that uses the context_menu.xml menu resource:

 

例如,这里有一个onCreateContextMenu(),使用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 inflate the context menu from a menu resource. (You can also use add() to add menu items.) The callback method parameters include the View that the user selected and a ContextMenu.ContextMenuInfo object that provides additional information about the item selected. You might use these parameters to determine which context menu should be created, but in this example, all context menus for the activity are the same.

 

MenuInflater被用于从菜单资源中解压出上下文菜单。(你还可以使用add()添加菜单条目。)回调方法参数包含用户选中的View和提供关于选中条目的额外信息的ContextMenu.ContextMenuInfo对象。你可以使用这些参数决定哪个上下文菜单一个被创建,但在这个示例中,活动的所有上下文菜单都是相同的。

 

Then when the user selects an item from the context menu, the system calls onContextItemSelected(). Here is an example of how you can handle selected items:

 

然后当用户从上下文菜单中选中一个条目时,系统调用onContextItemSelected()。这里有一个示例,演示你可以如何处理选中的条目:

 

-------------------------------

 

@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);

  }

}

 

-------------------------------

 

The structure of this code is similar to the example for Creating an Options Menu, in which getItemId() queries the ID for the selected menu item and a switch statement matches the item to the IDs that are defined in the menu resource. And like the options menu example, the default statement calls the super class in case it can handle menu items not handled here, if necessary.

 

这段代码的结构类似于创建选项菜单的示例,其中getItemId()查询选中菜单条目的ID而switch语句匹配条目和定义在菜单资源中的ID。而像选项菜单示例那样,如果有必要,它能处理在这里不被处理的菜单条目的话,default语句调用超类。

 

In this example, the selected item is an item from a ListView. To perform an action on the selected item, the application needs to know the list ID for the selected item (it's position in the ListView). To get the ID, the application calls getMenuInfo(), which returns a AdapterView.AdapterContextMenuInfo object that includes the list ID for the selected item in the id field. The local methods editNote() and deleteNote() methods accept this list ID to perform an action on the data specified by the list ID.

 

在这个示例中,选中的条目是来自ListView的一个条目。为了在选中条目上执行动作,应用程序需要知道选中条目的列表ID(它是在ListView中的位置)。为了获取ID,应用程序调用getMenuInfo(),它返回一个AdapterView.AdapterContextMenuInfo对象在id字段中包含选中条目的列表ID。局部方法editNote()和deleteNote()方法接受这个列表ID以对列表ID指定的数据执行一个动作。

 

-------------------------------

 

Note: Items in a context menu do not support icons or shortcut keys.

 

注意:上下文菜单中的条目不支持图标或快捷键。

 

-------------------------------

 

-------------------------------

 

Creating Submenus

 

创建子菜单

 

A submenu is a menu that the user can open by selecting an item in another menu. You can add a submenu to any menu (except a submenu). Submenus are useful when your application has a lot of functions that can be organized into topics, like items in a PC application's menu bar (File, Edit, View, etc.).

 

子菜单是一种菜单,用户可以通过选中另一个菜单中的条目来打开。你可以添加一个子菜单到任意菜单(除了子菜单)。子菜单是有用的,当你的应用程序拥有很多可以组织进不同主题的功能,就像个人电脑应用程序的菜单栏中的条目(文件,编辑,查看,等等)。

 

When creating your menu resource, you can create a submenu by adding a <menu> element as the child of an <item>. For example:

 

当创建你的菜单资源时,你可以通过添加<menu>元素作为<item>的子元素来创建一个子菜单。例如:

 

-------------------------------

 

<?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 the user selects an item from a submenu, the parent menu's respective on-item-selected callback method receives the event. For instance, if the above menu is applied as an Options Menu, then the onOptionsItemSelected() method is called when a submenu item is selected.

 

当用户从一个子菜单中选中一个条目时,父菜单相应的条目选中回调方法接收该事件。例如,如果上面的菜单被应用作为选项菜单,那么当子菜单条目被选中时onOptionsItemSelected()方法被调用。

 

You can also use addSubMenu() to dynamically add a SubMenu to an existing Menu. This returns the new SubMenu object, to which you can add submenu items, using add()

 

你还可以使用addSubMenu()动态添加一个SubMenu到一个现存的Menu。它返回新的SubMenu的对象,你可以使用add()添加新子菜单条目到它。

 

-------------------------------

 

Other Menu Features

 

其它菜单特性

 

Here are some other features that you can apply to most menu items.

 

这里是其它一些特性,你可以应用它们到大多数菜单条目。

 

Menu groups

 

菜单组

 

A menu group is a collection of menu items that share certain traits. With a group, you can:

 

菜单组是共享某个特质的菜单条目的集合。使用组,你可以:

 

* Show or hide all items with setGroupVisible()

 

* 用setGroupVisible()显示或隐藏所有条目

 

* Enable or disable all items with setGroupEnabled()

 

* 用setGroupEnabled()使能和屏蔽所有条目

 

* Specify whether all items are checkable with setGroupCheckable()

 

* 用setGroupCheckable()指定所有条目是否是可勾选的

 

You can create a group by nesting <item> elements inside a <group> element in your menu resource or by specifying a group ID with the the add() method.

 

你可以通过在你的菜单资源中的<group>元素内内嵌<item>元素,或通过用add()方法指定一个组ID,创建一个组。

 

Here's an example menu resource that includes a group:

 

这里有一个示例菜单资源,包含一个组:

 

-------------------------------

 

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/item1"

          android:icon="@drawable/item1"

          android:title="@string/item1" />

    <!-- menu group -->

    <group android:id="@+id/group1">

        <item android:id="@+id/groupItem1"

              android:title="@string/groupItem1" />

        <item android:id="@+id/groupItem2"

              android:title="@string/groupItem2" />

    </group>

</menu>

 

-------------------------------

 

The items that are in the group appear the same as the first item that is not in a group—all three items in the menu are siblings. However, you can modify the traits of the two items in the group by referencing the group ID and using the methods listed above.

 

在一个组中的条目和不在一个组的第一个条目看起是相同的——菜单中所有三个条目是平行的。然而,你可以通过引用组ID和上面列举的方法修改该组内两个条目的特征。

 

Checkable menu items

 

可勾选的菜单条目

 

(图3略)

 

Figure 3. Screenshot of a submenu with checkable items.

 

图3. 带可勾选条目的子菜单的截屏。

 

A menu can be useful as an interface for turning options on and off, using a checkbox for stand-alone options, or radio buttons for groups of mutually exclusive options. Figure 2 shows a submenu with items that are checkable with radio buttons.

 

菜单可能作为一个切换选项开关的界面是有用的,对单独选项使用多选框,或对相互排斥的选项组使用单选框。图2展示一个带有单选按钮的可勾选条目的子菜单。

 

-------------------------------

 

Note: Menu items in the Icon Menu (from the Options Menu) cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, you must manually indicate the checked state by swapping the icon and/or text each time the state changes.

 

注意:图标菜单(来自选项菜单)中的菜单条目不能显示多选框或单选按钮。如果你决定让图标菜单中的条目可勾选,你必须在每次状态改变时通过交换图标和/或文本手动来指示其勾选状态。

 

-------------------------------

 

You can define the checkable behavior for individual menu items using the android:checkable attribute in the <item> element, or for an entire group with the android:checkableBehavior attribute in the <group> element. For example, all items in this menu group are checkable with a radio button:

 

你可以在<item>元素中使用android:checkable属性对单独的菜单条目定义可勾选行为,或对整个组在<group>元素中使用android:checkableBehavior属性。例如,此菜单组的所有条目作为单选按钮是可勾选的。

 

-------------------------------

 

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item android:id="@+id/red"

              android:title="@string/red" />

        <item android:id="@+id/blue"

              android:title="@string/blue" />

    </group>

</menu>

 

-------------------------------

 

The android:checkableBehavior attribute accepts either:

 

android:checkableBehavior属性可接受的值有:

 

* single

 

Only one item from the group can be checked (radio buttons)

 

组内只有一个条目可被勾选(单选按钮)

 

* all

 

All items can be checked (checkboxes)

 

所有条目可以被勾选(多选框)

 

* none

 

No items are checkable

 

没有条目是可勾选的

 

You can apply a default checked state to an item using the android:checked attribute in the <item> element and change it in code with the setChecked() method.

 

你可以在<item>元素中使用android:checked属性应用一个默认的勾选状态到一个条目,并且在代码中用setChecked()方法改变它。

 

When a checkable item is selected, the system calls your respective item-selected callback method (such as onOptionsItemSelected()). It is here that you must set the state of the checkbox, because a checkbox or radio button does not change its state automatically. You can query the current state of the item (as it was before the user selected it) with isChecked() and then set the checked state with setChecked(). For example:

 

当一个可勾选的条目被选中时,系统调用你相应的条目选中回调方法(诸如onOptionsItemSelected())。这里你必须设置勾选框的状态,因为多选框或单选框不自动改变它的状态。你可以用isChecked()查询当前的条目状态(用户选中它之前的状态),然后用setChecked()设置勾选状态。

 

-------------------------------

 

@Override

public boolean onOptionsItemSelected(MenuItem item) {

  switch (item.getItemId()) {

  case R.id.vibrate:

  case R.id.dont_vibrate:

    if (item.isChecked()) item.setChecked(false);

    else item.setChecked(true);

    return true;

  default:

    return super.onOptionsItemSelected(item);

  }

}

 

-------------------------------

 

If you don't set the checked state this way, then the visible state of the item (the checkbox or radio button) will not change when the user selects it. When you do set the state, the activity preserves the checked state of the item so that when the user opens the menu later, the checked state that you set is visible.

 

如果你不用这种方式设置勾选状态,那么条目(多选框或单选框)的可见状态在用户选中它时将不会改变。当你设置了状态时,该活动保留条目的勾选状态,致使当用户稍后打开菜单时,你设置的勾选状态是可见的。

 

-------------------------------

 

Note: Checkable menu items are intended to be used only on a per-session basis and not saved after the application is destroyed. If you have application settings that you would like to save for the user, you should store the data using Shared Preferences.

 

注意:可勾选菜单条目是倾向于被使用的,仅基于每个会话的基础上并且在应用程序被销毁后不保存。如果你希望为用户保存应用程序的设置,你应该使用共享预设保存数据。

 

-------------------------------

 

Shortcut keys

 

快捷键

 

To facilitate quick access to items in the Options Menu when the user's device has a hardware keyboard, you can add quick-access shortcut keys using letters and/or numbers, with the android:alphabeticShortcut and android:numericShortcut attributes in the <item> element. You can also use the methods setAlphabeticShortcut(char) and setNumericShortcut(char). Shortcut keys are not case sensitive.

 

为了便于快速访问选项菜单中的条目,当用户的设备拥有硬键盘时,你可以在<item>元素中使用android:alphabeticShortcut和android:numericShortcut属性,用字母和/或数字添加快速访问快捷键。你还可以使用方法setAlphabeticShortcut(char)和setNumericShortcut(char)。快捷键不是大小写敏感的。

 

For example, if you apply the "s" character as an alphabetic shortcut to a "save" menu item, then when the menu is open (or while the user holds the MENU button) and the user presses the "s" key, the "save" menu item is selected.

 

例如,如果你应用s字符作为“保存”菜单条目的字母快捷键,那么当菜单被打开(或当用户按住MENU键时)而用户按下s键,“保存”菜单条目被选中。

 

This shortcut key is displayed as a tip in the menu item, below the menu item name (except for items in the Icon Menu, which are displayed only if the user holds the MENU button).

 

此快捷键被显示在菜单条目中作为提示,在菜单条目名称下方(除了图标菜单中的条目外,它们仅当用户按住MENU键才被显示)。

 

-------------------------------

 

Note: Shortcut keys for menu items only work on devices with a hardware keyboard. Shortcuts cannot be added to items in a Context Menu.

 

注意:菜单条目的快捷键只工作于带有硬键盘的设备上。快捷键不能被添加到上下文菜单的条目中。

 

-------------------------------

 

Dynamically adding menu intents

 

动态添加菜单意图

 

Sometimes you'll want a menu item to launch an activity using an Intent (whether it's an activity in your application or another application). When you know the intent you want to use and have a specific menu item that should initiate the intent, you can execute the intent with startActivity() during the appropriate on-item-selected callback method (such as the onOptionsItemSelected() callback).

 

有时你希望一个菜单条目使用Intent对象启动一个活动(它是你的应用程序或另一个应用程序中的活动)。当你知道该意图,你希望使用和拥有一个应该启动该意图的特定菜单条目时,你可以在合适的条目选中回调方法(诸如onOptionsItemSelected()回调)期间用startActivity()执行意图。

 

However, if you are not certain that the user's device contains an application that handles the intent, then adding a menu item that invokes it can result in a non-functioning menu item, because the intent might not resolve to an activity. To solve this, Android lets you dynamically add menu items to your menu when Android finds activities on the device that handle your intent.

 

然而,如果你不确定用户的设备包含一个处理意图的应用程序,那么添加调用它的菜单条目可能导致一个无功能的菜单条目,因为意图不能解析到一个活动中。为了解析它,当Android在设备上找到能处理你的意图的活动时,Android让你动态地添加菜单条目到你的菜单。

 

To add menu items based on available activities that accept an intent:

 

为了基于接受意图的可用活动来添加菜单条目:

 

1. Define an intent with the category CATEGORY_ALTERNATIVE and/or CATEGORY_SELECTED_ALTERNATIVE, plus any other requirements.

 

1. 用分类CATEGORY_ALTERNATIVE和/或CATEGORY_SELECTED_ALTERNATIVE定义意图,加上其它任意必需品。

 

2. Call Menu.addIntentOptions(). Android then searches for any applications that can perform the intent and adds them to your menu.

 

2. 调用Menu.addIntentOptions()。然后Android搜索可以执行意图的所有应用程序并添加它们到你的菜单。

 

If there are no applications installed that satisfy the intent, then no menu items are added.

 

如果没有已安装的应用程序满足意图,就不添加菜单条目。

 

-------------------------------

 

Note: CATEGORY_SELECTED_ALTERNATIVE is used to handle the currently selected element on the screen. So, it should only be used when creating a Menu in onCreateContextMenu().

 

注意:使用CATEGORY_SELECTED_ALTERNATIVE处理屏幕上当前选中的元素。所以,仅当用onCreateContextMenu()创建菜单时才应该使用它。

 

-------------------------------

 

For example:

 

例如:

 

-------------------------------

 

@Override

public boolean onCreateOptionsMenu(Menu menu){

    super.onCreateOptionsMenu(menu);

 

    // Create an Intent that describes the requirements to fulfill, to be included

    // in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE.

    // 创建一个Intent对象描述要填充的必需品,它们要被包含在我们的菜单中。

    // 提供的应用必须包含Intent.CATEGORY_ALTERNATIVE的分类值。

    Intent intent = new Intent(null, dataUri);

    intent.addCategory(Intent.CATEGORY_ALTERNATIVE);

 

    // Search and populate the menu with acceptable offering applications.

    // 用可接受的提供的应用程序搜索并生成菜单

    menu.addIntentOptions(

         R.id.intent_group,  // Menu group to which new items will be added

         // 新条目将要添加到的菜单组

         0,      // Unique item ID (none)

         // 唯一的条目ID(无)

         0,      // Order for the items (none)

         // 条目排序(无)

         this.getComponentName(),   // The current activity name

         // 当前活动名称

         null,   // Specific items to place first (none)

         // 放在第一位的特定条目(无)

         intent, // Intent created above that describes our requirements

         // 前面创建的Intent对象,描述我们的需求。

         0,      // Additional flags to control items (none)

         // 额外标志用于控制条目(无)

         null);  // Array of MenuItems that correlate to specific items (none)

         //MenuItem数组,关联指定的条目(无)

 

    return true;

}

 

-------------------------------

 

For each activity found that provides an intent filter matching the intent defined, a menu item is added, using the value in the intent filter's android:label as the menu item title and the application icon as the menu item icon. The addIntentOptions() method returns the number of menu items added.

 

对于每个找到的提供匹配所定义意图的意图过滤器的活动,菜单条目被添加,使用意图过滤器的android:label的值作为菜单条目标题而应用程序图标作为菜单条目图标。addIntentOptions()方法返回被添加菜单条目的个数。

 

-------------------------------

 

Note: When you call addIntentOptions(), it overrides any and all menu items by the menu group specified in the first argument.

 

注意:当你调用addIntentOptions()时,它通过第一参数指定的菜单组覆盖任意和所有菜单条目。

 

-------------------------------

 

Allowing your activity to be added to other menus

 

允许你的活动被添加到其它菜单

 

You can also offer the services of your activity to other applications, so your application can be included in the menu of others (reverse the roles described above).

 

你还可以向其它应用程序提供你活动的服务,所以你的应用程序可以被包含在其它程序的菜单中(颠倒上面描述的角色)。

 

To be included in other application menus, you need to define an intent filter as usual, but be sure to include the CATEGORY_ALTERNATIVE and/or CATEGORY_SELECTED_ALTERNATIVE values for the intent filter category. For example:

 

为了被包含在其它应用程序菜单,你通常需要定义一个意图过滤器,但确保意图过滤器分类包含CATEGORY_ALTERNATIVE和/或CATEGORY_SELECTED_ALTERNATIVE值。例如:

 

-------------------------------

 

<intent-filter label="Resize Image">

    ...

    <category android:name="android.intent.category.ALTERNATIVE" />

    <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />

    ...

</intent-filter>

 

-------------------------------

 

Read more about writing intent filters in the Intents and Intent Filters document.

 

请在意图和意图过滤器文档中阅读更多关于书写意图过滤器的信息。

 

For a sample application using this technique, see the Note Pad sample code.

 

想获取使用这种技术的示例应用程序,请参见记事本示例代码。

 

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

 

除特别说明外,本文在Apache 2.0下许可。细节和限制请参考内容许可证。

 

Android 4.0 r1 - 17 Nov 2011 21:59

 

(Android 4.0 r1 - 01 Feb 2012 20:50改动太大,故废弃)

 

Site Terms of Service - Privacy Policy - Brand Guidelines

 

-------------------------------

 

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

 

(此页部分内容基于Android开源项目,以及使用根据创作公共2.5来源许可证描述的条款进行修改)

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics