`

【翻译】(15)菜单

 
阅读更多

【翻译】(15)菜单

 

see

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

 

原文见

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

 

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

 

Menus

 

菜单

 

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

 

In this document

 

本文目录

 

* Defining a Menu in XML 在XML中定义一个菜单

* Creating an Options Menu 创建一个选项菜单

* Handling click events 处理点击事件

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

* Creating Contextual Menus 创建上下文相关菜单

* Creating a floating context menu 创建一个浮动的上下文菜单

* Using the contextual action mode 使用上下文相关动作模式

* Creating a Popup Menu 创建一个弹出菜单

* Handling click events 处理点击事件

* Creating Menu Groups 创建菜单组

* Using checkable menu items 使用可勾选菜单条目

* Adding Menu Items Based on an Intent 基于一个意图添加菜单条目

* Allowing your activity to be added to other menus 允许添加你的活动到其它菜单

 

Key classes

 

关键类

 

Menu

MenuItem

ContextMenu

ActionMode

 

See also

 

另见

 

Action Bar 动作栏

Menu Resource 菜单资源

Say Goodbye to the Menu Button 告别菜单按钮

 

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

 

Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, you should use the Menu APIs to present user actions and other options in your activities.

 

菜单是一种在许多应用程序类型中通用的用户界面组件。为了提供一个熟悉的和一致的用户体验,你应该使用Menu API来呈现你的活动中的用户动作和其它选项。

 

Beginning with Android 3.0 (API level 11), Android-powered devices are no longer required to provide a dedicated Menu button. With this change, Android apps should migrate away from a dependence on the traditional 6-item menu panel and instead provide an action bar to present common user actions.

 

从Android 3.0(API级别11)开始,不再需要基于Android的设备提供一个专门的菜单按钮。对于此改变,Android应用应该迁移离开对传统6条目菜单面板的依赖,并且取而代之,提供一个动作栏以呈现通用的用户动作。

 

Although the design and user experience for some menu items have changed, the semantics to define a set of actions and options is still based on the Menu APIs. This guide shows how to create the three fundamental types of menus or action presentations on all versions of Android:

 

虽然对于一些菜单条目的设计和用户体验已经改变,定义一组动作和选项的语义仍然基于Menu API。本指引展示如何在所有Android版本上创建三种基本类型的菜单或动作表现:

 

* Options menu and action bar

 

* 选项菜单和动作栏

 

The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings."

 

选项菜单是对于一个活动的菜单条目的主集合。你应该在这里放置在应用上拥有一个全局影响力的动作,诸如“搜索”,“撰写电子邮件”,以及“设置”。

 

If you're developing for Android 2.3 or lower, users can reveal the options menu panel by pressing the Menu button.

 

如果你正在为Android 2.3或更低版本开发,用户可以通过按菜单按钮来展开选项菜单面板。

 

On Android 3.0 and higher, items from the options menu are presented by the action bar as a combination of on-screen action items and overflow options. Beginning with Android 3.0, the Menu button is deprecated (some devices don't have one), so you should migrate toward using the action bar to provide access to actions and other options.

 

在Android 3.0和更高版本上,来自选项菜单的条目由动作栏来呈现作为一个屏幕上动作条目和溢出选项的组合。从Android 3.0开始,菜单按钮被废弃(一些设备没有它),所以你应该迁移到使用动作栏以提供对动作和其它选项的访问。

 

See the section about Creating an Options Menu.

 

见关于创建一个选项菜单的章节。

 

* Context menu and contextual action mode

 

* 上下文菜单和上下文相关动作模式

 

A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.

 

一个上下文菜单是一个浮动的菜单,它在用户在一个元素上执行一个长点击时出现。它提供影响被选择内容或上下文框架的动作。

 

When developing for Android 3.0 and higher, you should instead use the contextual action mode to enable actions on selected content. This mode displays action items that affect the selected content in a bar at the top of the screen and allows the user to select multiple items.

 

当为Android 3.0和更高开发时,取而代之你应该使用上下文相关动作模式以使能被选择内容上的动作。这个模式在屏幕顶部的一个栏中显示影响被选择内容的动作条目,并且允许用户选择多个条目。

 

See the section about Creating Contextual Menus.

 

参见关于创建上下文相关菜单的章节。

 

* Popup menu

 

* 弹出菜单

 

A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu. It's good for providing an overflow of actions that relate to specific content or to provide options for a second part of a command. Actions in a popup menu should not directly affect the corresponding content—that's what contextual actions are for. Rather, the popup menu is for extended actions that relate to regions of content in your activity.

 

一个弹出菜单显示一列条目在一个垂直列表中,它固定到(注:待考)调用菜单的视图。它有利于提供一个与指定内容相关的动作的溢出显示或提供对一个命令的第二部分的选项。一个弹出菜单里的动作不应该直接地影响相应的内容——那是上下文相关动作的作用。相反,弹出菜单是用于与你的活动里的内容的区域有关的扩展动作。

 

See the section about Creating a Popup Menu.

 

参见关于创建一个弹出菜单的章节

 

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

 

Defining a Menu in XML

 

在XML中定义一个菜单

 

For all menu types, Android provides a standard XML format to define menu items. Instead of building a menu in your activity's code, you should define a menu and all its items in an XML menu resource. You can then inflate the menu resource (load it as a Menu object) in your activity or fragment.

 

对于所有菜单类型,Android提供一种标准XML格式来定义菜单条目。取代在你的活动的代码中构建一个菜单,你应该在一个XML菜单资源中定义一个菜单和它的所有条目。然后你可以在你的活动或片段中解压菜单资源(加载它作为一个Menu对象)。

 

Using a menu resource is a good practice for a few reasons:

 

使用一个菜单资源是一个好的实践,因为一些原因:

 

* It's easier to visualize the menu structure in XML.

 

* 在XML中较容易地可视化菜单结构。

 

* It separates the content for the menu from your application's behavioral code.

 

* 它从你的应用程序的行为代码中分离出菜单内容。

 

* It allows you to create alternative menu configurations for different platform versions, screen sizes, and other configurations by leveraging the app resources framework.

 

* 它允许你通过利用应用资源框架为不同平台版本,屏幕大小,和其它配置创建可选菜单配置。

 

To define the menu, 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,它是一个用于菜单条目的容器。一个<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. For more information, see the section about Creating 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"

          android:showAsAction="ifRoom"/>

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

          android:icon="@drawable/ic_help"

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

</menu>

 

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

 

The <item> element supports several attributes you can use to define an item's appearance and behavior. The items in the above menu include the following attributes:

 

<item>元素支持几个属性,你可以使用它们来定义一个条目的外观和行为。上面菜单中的条目包括以下属性:

 

* 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.

 

一个指向字符串的引用以用作该条目的标题。

 

* android:showAsAction

 

Specifies when and how this item should appear as an action item in the action bar.

 

指定这个条目应该何时和如何出现作为动作栏中的一个动作条目。

 

These are the most important attributes you should use, but there are many more available. For information about all the supported attributes, see the Menu Resource document.

 

这些是你应该使用的最重要的属性,但还有更多可用的。想获取关于所有被支持的属性的信息,请参见菜单资源文档。

 

You can add a submenu to an item in any menu (except a submenu) by adding a <menu> element as the child of an <item>. 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.). For example:

 

你可以通过添加一个<menu>元素作为一个<item>的子元素来添加一个子菜单到任意菜单(除了子菜单)中的一个条目。当你的应用程序有许多功能,它们可以被组织进多个主题,就像一个PC应用程序的菜单栏里的条目(文件,编辑,查看,等等)那样时,子菜单是有用的。例如:

 

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

 

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

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

    <item android:id="@+id/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>

 

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

 

To use the menu in your activity, you need to inflate the menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate(). In the following sections, you'll see how to inflate a menu for each menu type.

 

为了在你的活动中创建菜单,你需要使用MenuInflater.inflate()解压菜单资源(转换XML资源为一个可编程的对象)。在以下章节中,你将看到如何对每种菜单类型解压菜单。

 

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

 

Creating an Options Menu

 

创建一个选项菜单

 

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

 

(图略:

浏览器google主页下方出现六条目选项菜单,含More溢出项。

 

Figure 1. Options menu in the Browser, on Android 2.3.

 

图1. 浏览器中的选项菜单,在Android 2.3上。

 

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

 

The options menu is where you should include actions and other options that are relevant to the current activity context, such as "Search," "Compose email," and "Settings."

 

在选项菜单中,你应该包含与当前活动上下文相关的动作和其它选项,诸如“搜索”,“撰写电子邮件”,和“设置”。

 

Where the items in your options menu appear on the screen depends on the version for which you've developed your application:

 

你的选项菜单中的条目在屏幕上的哪里出现依赖于你开发你的应用程序所为了的版本:

 

* If you've developed your application for Android 2.3.x (API level 10) or lower, the contents of your options menu appear at the bottom of the screen when the user presses the Menu button, as shown in figure 1. When opened, the first visible portion is the icon menu, which holds up to six menu items. If your menu includes more than six items, Android places the sixth item and the rest into the overflow menu, which the user can open by selecting More.

 

* 如果你开发你的应用程序是为了Android 2.3.x(API级别10)或更低,那么当用户按下菜单按钮时你的选项菜单出现在屏幕的底部,正如图1所示。当被打开时,最先可见的部分是图标菜单,它持有持有最多六个菜单条目,如果你的菜单包含多余六个条目,那么Android把第六个条目和其它条目放进溢出菜单中,用户可以通过选择更多来打开它。

 

* If you've developed your application for Android 3.0 (API level 11) and higher, items from the options menu are available in the action bar. By default, the system places all items in the action overflow, which the user can reveal with the action overflow icon on the right side of the action bar (or by pressing the device Menu button, if available). To enable quick access to important actions, you can promote a few items to appear in the action bar by adding android:showAsAction="ifRoom" to the corresponding <item> elements (see figure 2).

 

* 如果你开发你的应用是为了Android 3.0(API级别11)和更高,那么来自选项菜单的条目在动作栏中可用。默认,系统放置所有条目在动作溢出中,用户可以用动作栏右侧上动作溢出图标来展开它(或者通过按设备的菜单按钮,如果它可用)。为了使能对重要动作的快速访问,你可以通过添加android:showAsAction="ifRoom"到相应的<item>元素来提升一些条目以显示在动作栏中(见图2)。

 

For more information about action items and other action bar behaviors, see the Action Bar guide.

 

想获取关于动作条目和其它动作栏行为的更多信息,请参见动作栏指引。

 

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

 

Note: Even if you're not developing for Android 3.0 or higher, you can build your own action bar layout for a similar effect. For an example of how you can support older versions of Android with an action bar, see the Action Bar Compatibility sample.

 

注意:即便你不是正在为Android 3.0或更高而开发,你仍可以构建你自己的动作栏布局以获得相似的效果。想获取你如何可以用一个动作栏支持旧版本的Android的示例,请参见动作栏兼容性示例。

 

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

 

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

 

(图略:

平板顶部的长条动作栏,带Logo、标签页、摄影图标,以及溢出按钮。

 

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

 

图2. 来自蜂巢画廊应用的动作栏,显示导航标签页和一个照相机动作条目(加上动作溢出按钮)。

 

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

 

You can declare items for the options menu from either your Activity subclass or a Fragment subclass. If both your activity and fragment(s) declare items for the options menu, they are combined in the UI. The activity's items appear first, followed by those of each fragment in the order in which each fragment is added to the activity. If necessary, you can re-order the menu items with the android:orderInCategory attribute in each <item> you need to move.

 

你可以声明来自你的Activity子类或一个Fragment子类的选项菜单的条目。如果你的活动和片段都声明了选项菜单的条目,那么它们被组合进用户界面。活动的条目最先出现,接着依次是每个片段的条目,其中每个片段被添加到活动(注:待考)。如果需要的话,你可以用你需要移动的每个<item>中的android:orderInCategory属性重新排序菜单条目。

 

To specify the options menu for an activity, override onCreateOptionsMenu() (fragments provide their own onCreateOptionsMenu() callback). In this method, you can inflate your menu resource (defined in XML) into the Menu provided in the callback. For example:

 

要想指定活动的选项菜单,请覆盖onCreateOptionsMenu()(片段提供它们自己的onCreateOptionsMenu()回调)。在这个方法中,你可以解压你的菜单资源(定义在XML中)进回调中提供的Menu对象。例如:

 

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

 

@Override

public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();

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

    return true;

}

 

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

 

You can also add menu items using add() and retrieve items with findItem() to revise their properties with MenuItem APIs.

 

你还可以使用add()添加菜单条目和用findItem()取出条目以用MenuItem的API修正它们的属性。

 

If you've developed your application for Android 2.3.x and lower, the system calls onCreateOptionsMenu() to create the options menu when the user opens the menu for the first time. If you've developed for Android 3.0 and higher, the system calls onCreateOptionsMenu() when starting the activity, in order to show items to the action bar.

 

如果你为Android 2.3.x和更低版本开发你的应用程序,那么当用户第一次打开菜单时系统调用onCreateOptionsMenu()以创建选项菜单。如果你已经为Android 3.0和更高版本开发,那么当启动活动时系统调用onCreateOptionsMenu(),以便显示条目到动作栏。

 

Handling click events

 

处理点击事件

 

When the user selects an 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 selected. You can identify the 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 to 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);

    }

}

 

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

 

When you successfully handle a menu item, return true. If you don't handle the menu item, you should call the superclass implementation of onOptionsItemSelected() (the default implementation returns false).

 

当你成功地处理一个菜单条目时,返回true。如果你不处理该菜单条目,你应该调用onOptionsItemSelected()的超类实现(默认实现返回false)。

 

If your activity includes fragments, the system first calls onOptionsItemSelected() for the activity then for each fragment (in the order each fragment was added) until one returns true or all fragments have been called.

 

如果你的活动包含片段,那么系统首先对该活动调用onOptionsItemSelected()然后才是对每个片段调用它(依照每个片段被添加的次序)直至其中一个返回true或所有片段都已经被调用过。

 

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

 

Tip: Android 3.0 adds the ability for you to define the on-click behavior for a menu item in XML, using the android:onClick attribute. The value for the attribute must be the name of a method defined by the activity using the menu. The method must be public and accept a single MenuItem parameter—when the system calls this method, it passes the menu item selected. For more information and an example, see the Menu Resource document.

 

提示:Android 3.0为你添加能力以在XML中对一个菜单条目定义点击行为,使用android:onClick属性。该属性的值必须是被使用菜单的活动定义的方法的名称。方法必须是public并且接受一个单一的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 can manage one set of code for handling menu actions and each descendant class inherits the menu behaviors. If you want to add menu items to one of the 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()和onOptionsItemSelected()方法外什么都不实现。然后为每个应该共享相同选项菜单的活动扩展这个类。通过这种方式,你可以管理一组用于处理菜单动作的代码而且每个后代类继承菜单行为。如果你希望添加菜单条目到其中一个后代活动,请覆盖那个活动中的onCreateOptionsMenu()。调用super.onCreateOptionsMenu(menu)使原来的菜单条目被创建,然后用menu.add()添加新的菜单条目。你还可以覆盖超类对单个菜单条目的行为。

 

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

 

Changing menu items at runtime

 

在运行时改变菜单条目

 

After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.

 

在系统调用onCreateOptionsMenu()后,它保持你填充的Menu的一个实例并且将不再调用onCreateOptionsMenu()除非菜单因为一些原因而不可用。然而,你应该只把onCreateOptionsMenu()用于创建最初的菜单状态并且在活动的生命周期期间不作出改变。

 

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)

 

如果你希望基于在活动生命周期期间发生的事件来修改选项菜单,那么你可以在onPrepareOptionsMenu()方法中这样做。这个方法传给你Menu对象当它当前存在时,使你可以修改它,诸如添加,移除,或屏蔽条目。(片段也提供一个onPrepareOptionsMenu()回调。)

 

On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).

 

在Android 2.3.x和更低上,每当用户打开选项菜单(按菜单按钮)时系统调用onPrepareOptionsMenu()。

 

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

 

在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.

 

注意:你应该从不基于当前获得焦点的View来改变选项菜单中的条目。当处于触碰模式时(当用户不使用一个轨迹球或方向板时),视图不允许获得焦点,所以你应该从不使用焦点作为修改选项菜单中的条目的基准。如果你希望提供对于一个View是上下文敏感的菜单条目,请使用一个上下文菜单。

 

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

 

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

 

Creating Contextual Menus

 

创建上下文相关菜单

 

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

 

(图略:

左图是浮动的上下文菜单,只有文本。

右图是右上角的动作栏,只有图标。

分别代表编辑、共享和删除。

 

Figure 3. Screenshots of a floating context menu (left) and the contextual action bar (right).

 

图3. 浮动上下文菜单(左)和上下文相关动作栏(右)的截屏。(注:右图应该是指右上角的三个图标,代表左图中的编辑、共享、删除三个条目)

 

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

 

A contextual menu offers actions that affect a specific item or context frame in the UI. You can provide a context menu for any view, but they are most often used for items in a ListView, GridView, or other view collections in which the user can perform direct actions on each item.

 

一个上下文相关菜单提供影响一个特定条目的动作或在用户界面中的上下文框架。你可以为任意视图提供一个上下文菜单,但它们最常被用于一个ListView,GridView或其它视图集合里的条目,其中用户可以在每个条目上执行直接的动作。

 

There are two ways to provide contextual actions:

 

有两种方式提供上下文相关动作:

 

* In a floating context menu. A menu appears as a floating list of menu items (similar to a dialog) when the user performs a long-click (press and hold) on a view that declares support for a context menu. Users can perform a contextual action on one item at a time.

 

* 在一个浮动上下文菜单中。当用户在一个声明支持上下文菜单的视图上执行一个长点击(按下并按住)时一个菜单作为菜单条目的浮动列表出现(类似于一个对话框)。用户可以每次在一个条目上执行一个上下文相关动作。

 

* In the contextual action mode. This mode is a system implementation of ActionMode that displays a contextual action bar at the top of the screen with action items that affect the selected item(s). When this mode is active, users can perform an action on multiple items at once (if your app allows it).

 

* 在上下文相关动作模式中。这种模式是ActionMode的系统实现,它显示一个上下文相关动作栏在屏幕的顶部,带有影响被选择条目的动作条目。当这个模式被激活时,用户可以马上在多个条目上执行一个动作(如果你的应用允许它)。

 

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

 

Note: The contextual action mode is available on Android 3.0 (API level 11) and higher and is the preferred technique for displaying contextual actions when available. If your app supports versions lower than 3.0 then you should fall back to a floating context menu on those devices.

 

注意:上下文相关动作模式在Android 3.0(API级别11)及更高上可用,并且是当它可用时用于显示上下文相关动作的首选技术。如果你的应用支持版本低于3.0,那么你应该在那些设备上倒退回一个浮动上下文菜单。

 

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

 

Creating a floating context menu

 

创建一个浮动的上下文菜单

 

To provide a floating context menu:

 

为了提供一个浮动上下文菜单:

 

1. Register the View to which the context menu should be associated by calling registerForContextMenu() and pass it the View.

 

1. 注册上下文菜单应该关联到的View,通过调用registerForContextMenu()并传给它那个View。

 

If your activity uses a ListView or GridView and you want each item to provide the same context menu, register all items for a context menu by passing the ListView or GridView to registerForContextMenu().

 

如果你的活动使用一个ListView或GridView而你希望每个条目提供相同的上下文菜单,请通过传递该ListView或GridView到registerForContextMenu()来注册一个上下文菜单的所有条目。

 

2. Implement the onCreateContextMenu() method in your Activity or Fragment.

 

2. 在你的Activity或Fragment中实现onCreateContextMenu()方法。

 

When the registered view receives a long-click event, the system calls your onCreateContextMenu() method. This is where you define the menu items, usually by inflating a menu resource. For example:

 

当被注册的视图接收到一个长点击事件时,系统调用你的onCreateContextMenu()方法。在这里你定义菜单条目,通常通过解压一个菜单资源。例如:

 

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

 

@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 allows you to inflate the context menu from a menu resource. The callback method parameters include the View that the user selected and a ContextMenu.ContextMenuInfo object that provides additional information about the item selected. If your activity has several views that each provide a different context menu, you might use these parameters to determine which context menu to inflate.

 

MenuInflater允许你从一个菜单资源中解压上下文菜单。回调方法参数包含用户选中的View和一个提供关于被选中条目的附加信息的ContextMenu.ContextMenuInfo对象。如果你的活动拥有几个视图,其中每个提供一个不同的上下文菜单,那么你可能使用这些参数来决定要解压哪个上下文菜单。

 

3. Implement onContextItemSelected().

 

3. 实现onContextItemSelected()。

 

When the user selects a menu item, the system calls this method so you can perform the appropriate action. For example:

 

当用户选中一个菜单条目时,系统调用此方法使你可以执行合适的动作。例如:

 

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

 

@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 getItemId() method queries the ID for the selected menu item, which you should assign to each menu item in XML using the android:id attribute, as shown in the section about Defining a Menu in XML.

 

getItemId()方法查询被选择菜单条目的ID,你应该在XML中使用android:id属性赋予它到每个菜单条目,正如关于在XML中定义一个菜单的章节所示。

 

When you successfully handle a menu item, return true. If you don't handle the menu item, you should pass the menu item to the superclass implementation. If your activity includes fragments, the activity receives this callback first. By calling the superclass when unhandled, the system passes the event to the respective callback method in each fragment, one at a time (in the order each fragment was added) until true or false is returned. (The default implementation for Activity and android.app.Fragment return false, so you should always call the superclass when unhandled.)

 

当你成功地处理一个菜单条目时,返回true。如果你不处理菜单条目,你应该传递菜单条目到超类实现。如果你的活动包含片段,活动首先接收这个回调。通过在未处理时调用超类,系统传递事件到每个片段中相应的回调方法,一次一个(依照每个片段的被添加次序)直至true或false被返回。(Activity和android.app.Fragment的默认实现返回false,所以当未处理时你应该调用超类。)

 

Using the contextual action mode

 

使用上下文相关动作模式

 

The contextual action mode is a system implementation of ActionMode that focuses user interaction toward performing contextual actions. When a user enables this mode by selecting an item, a contextual action bar appears at the top of the screen to present actions the user can perform on the currently selected item(s). While this mode is enabled, the user can select multiple items (if you allow it), deselect items, and continue to navigate within the activity (as much as you're willing to allow). The action mode is disabled and the contextual action bar disappears when the user deselects all items, presses the BACK button, or selects the Done action on the left side of the bar.

 

上下文相关动作模式是ActionMode的一个系统实现,它把用户界面的焦点集中到执行上下文相关动作上。当一位用户通过选中一个条目使能这个模式时,一个上下文相关动作栏出现在屏幕的顶部以呈现用户可以在当前选中的条目上执行的动作。当这个模式被使能的时候,用户可以选择多个条目(如果你允许它),取消选择条目,并且在活动中继续导航(尽你所期望允许的程度)(注:待考)。当用户取消选择所有条目,按后退键,或选择栏的左侧上的Done(注:完成)动作时动作模式被屏蔽而上下文相关动作栏消失。

 

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

 

Note: The contextual action bar is not necessarily associated with the action bar. They operate independently, even though the contextual action bar visually overtakes the action bar position.

 

注意:上下文相关动作栏不一定与动作栏关联。它们独立地操作,即便上下文相关动作栏可视地占据了动作栏的位置。

 

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

 

If you're developing for Android 3.0 (API level 11) or higher, you should usually use the contextual action mode to present contextual actions, instead of the floating context menu.

 

如果你正在为Android 3.0(API级别11)或更高的版本开发,你应该通常地使用上下文相关动作模式来呈现上下文相关动作,而非浮动上下文菜单。

 

For views that provide contextual actions, you should usually invoke the contextual action mode upon one of two events (or both):

 

对于提供上下文相关动作的视图,你应该通常地在两个事件之一(或两者)上调用上下文相关动作模式:

 

* The user performs a long-click on the view.

 

* 用户在视图上执行一个长点击

 

* The user selects a checkbox or similar UI component within the view.

 

* 用户选择一个复选框或视图中类似的用户界面组件。

 

How your application invokes the contextual action mode and defines the behavior for each action depends on your design. There are basically two designs:

 

你的应用程序如何调用上下文相关动作模式以及为每个动作定义行为,依赖于你的设计。基本上有两种设计:

 

* For contextual actions on individual, arbitrary views.

 

* 针对个别的、任意视图上的上下文相关动作。

 

* For batch contextual actions on groups of items in a ListView or GridView (allowing the user to select multiple items and perform an action on them all).

 

* 针对一个ListView或GridView中的条目分组上的批量上下文相关动作(允许用户选择多个条目并在它们全体上执行一个动作)

 

The following sections describe the setup required for each scenario.

 

以下章节描述每个场景所需要的配置。

 

Enabling the contextual action mode for individual views

 

使能用于个别视图的上下文相关动作模式

 

If you want to invoke the contextual action mode only when the user selects specific views, you should:

 

如果你希望仅当用户选择特定视图时才调用上下文相关动作模式,你应该:

 

1. Implement the ActionMode.Callback interface. In its callback methods, you can specify the actions for the contextual action bar, respond to click events on action items, and handle other lifecycle events for the action mode.

 

1. 实现ActionMode.Callback接口。在它的回调方法中,你可以为上下文相关动作栏指定动作,响应动作条目上的点击事件,并且处理动作模式的其它生命周期事件。

 

2. Call startActionMode() when you want to show the bar (such as when the user long-clicks the view).

 

2. 当你希望显示该栏时调用startActionMode()(诸如当用户长点击视图时)。

 

For example:

 

例如:

 

1. Implement the ActionMode.Callback interface:

 

1. 实现ActionMode.Callback接口:

 

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

 

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

 

    // Called when the action mode is created; startActionMode() was called

    // 当动作模式被创建时被调用;startActionMode()被调用

    @Override

    public boolean onCreateActionMode(ActionMode mode, Menu menu) {

        // Inflate a menu resource providing context menu items

        // 解压一个提供上下文菜单条目的菜单资源

        MenuInflater inflater = mode.getMenuInflater();

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

        return true;

    }

 

    // Called each time the action mode is shown. Always called after onCreateActionMode, but

    // may be called multiple times if the mode is invalidated.

    // 每当动作模式被展示时被调用。总是在onCreateActionMode之后被调用,但

    // 可能被调用多次,如果模式被无效化。

    @Override

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

        return false; // Return false if nothing is done 返回false如果没有完成事情

    }

 

    // Called when the user selects a contextual menu item

    // 当用户选择一个上下文相关菜单条目时被调用

    @Override

    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

        switch (item.getItemId()) {

            case R.id.menu_share:

                shareCurrentItem();

                mode.finish(); // Action picked, so close the CAB 动作被拾取,所以关闭上下文相关动作栏(注:这里的CAB貌似是contextual action bar的缩写)

                return true;

            default:

                return false;

        }

    }

 

    // Called when the user exits the action mode

    // 当用户退出动作模式时被调用

    @Override

    public void onDestroyActionMode(ActionMode mode) {

        mActionMode = null;

    }

};

 

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

 

Notice that these event callbacks are almost exactly the same as the callbacks for the options menu, except each of these also pass the ActionMode object associated with the event. You can use ActionMode APIs to make various changes to the CAB, such as revise the title and subtitle with setTitle() and setSubtitle() (useful to indicate how many items are selected).

 

注意这些事件回调大多数与选项菜单的回调相同,除了这些回调中的每一个还传进与事件关联的ActionMode对象。你可以使用ActionMode的API来对上下文相关动作栏作出不同的改变,诸如用setTitle()和setSubtitle()修改标题和副标题(对于指示多少条目被选中来说有用)。

 

Also notice that the above sample sets the mActionMode variable null when the action mode is destroyed. In the next step, you'll see how it's initialized and how saving the member variable in your activity or fragment can be useful.

 

还要注意上面的示例在动作模式被销毁时设置mActionMode变量为null。在下一步中,你将看到如何初始化它以及如何保存你的活动或片段中的成员变量可以是有用的。

 

2. Call startActionMode() to enable the contextual action mode when appropriate, such as in response to a long-click on a View:

 

2. 当合适的时候调用startActionMode()以使能上下文相关模式,诸如响应一个View上的一个长点击:

 

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

 

someView.setOnLongClickListener(new View.OnLongClickListener() {

    // Called when the user long-clicks on someView

    // 当用户在someView上长按时被调用

    public boolean onLongClick(View view) {

        if (mActionMode != null) {

            return false;

        }

 

        // Start the CAB using the ActionMode.Callback defined above

        // 使用上面定义的ActionMode.Callback启动上下文相关动作栏

        mActionMode = getActivity().startActionMode(mActionModeCallback);

        view.setSelected(true);

        return true;

    }

});

 

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

 

When you call startActionMode(), the system returns the ActionMode created. By saving this in a member variable, you can make changes to the contextual action bar in response to other events. In the above sample, the ActionMode is used to ensure that the ActionMode instance is not recreated if it's already active, by checking whether the member is null before starting the action mode.

 

当你调用startActionMode()时,系统返回被创建的ActionMode。通过在一个成员变量中保存它,你可以对上下文相关动作栏作出改变以响应其它事件。在上面的示例中,ActionMode被用于确保ActionMode实例不被重新创建如果它已经激活,通过在启动动作模式前检查成员是否为null。

 

Enabling batch contextual actions in a ListView or GridView

 

在一个ListView或GridView中使能批量上下文动作

 

If you have a collection of items in a ListView or GridView (or another extension of AbsListView) and want to allow users to perform batch actions, you should:

 

如果你在一个ListView或GridView(或另一个AbsListView扩展类)中拥有一组条目并且希望允许用户执行批量动作,你应该:

 

* Implement the AbsListView.MultiChoiceModeListener interface and set it for the view group with setMultiChoiceModeListener(). In the listener's callback methods, you can specify the actions for the contextual action bar, respond to click events on action items, and handle other callbacks inherited from the ActionMode.Callback interface.

 

* 实现AbsListView.MultiChoiceModeListener接口并且对视图组用setMultiChoiceModeListener()设置它。在监听器的回调方法中,你可以指定上下文相关动作栏的动作,响应动作条目上的点击事件,并且处理继承自ActionMode.Callback接口的其它回调。

 

* Call setChoiceMode() with the CHOICE_MODE_MULTIPLE_MODAL argument.

 

* 用CHOICE_MODE_MULTIPLE_MODAL参数调用setChoiceMode()。

 

For example:

 

例如:

 

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

 

ListView listView = getListView();

listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

 

    @Override

    public void onItemCheckedStateChanged(ActionMode mode, int position,

                                          long id, boolean checked) {

        // Here you can do something when items are selected/de-selected,

        // such as update the title in the CAB

        // 在这里当条目被选择/取消选择时你可以做一些事情,

        // 诸如更新上下文相关动作栏里的标题

    }

 

    @Override

    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

        // Respond to clicks on the actions in the CAB

        // 响应上下文相关动作栏中动作上的点击

        switch (item.getItemId()) {

            case R.id.menu_delete:

                deleteSelectedItems();

                mode.finish(); // Action picked, so close the CAB 动作被拾取,所以关闭上下文相关动作栏

                return true;

            default:

                return false;

        }

    }

 

    @Override

    public boolean onCreateActionMode(ActionMode mode, Menu menu) {

        // Inflate the menu for the CAB

        // 解压用于上下文相关动作栏的菜单

        MenuInflater inflater = mode.getMenuInflater();

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

        return true;

    }

 

    @Override

    public void onDestroyActionMode(ActionMode mode) {

        // Here you can make any necessary updates to the activity when

        // the CAB is removed. By default, selected items are deselected/unchecked.

        // 在这里当上下文相关动作栏被移除时你可以对活动做出任意必需的更新。

        // 默认,被选择的条目被取消选择/取消勾选。

    }

 

    @Override

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

        // Here you can perform updates to the CAB due to

        // an invalidate() request

        // 在这里你可以因为一个invalidate()请求而对上下文相关动作栏执行更新

        return false;

    }

});

 

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

 

That's it. Now when the user selects an item with a long-click, the system calls the onCreateActionMode() method and displays the contextual action bar with the specified actions. While the contextual action bar is visible, users can select additional items.

 

就是这样。现在当用户用长点击选中一个条目时,系统调用onCreateActionMode()方法并用特定的方法显示上下文相关动作栏。当上下文相关动作栏可见时,用户可以选择附加条目。

 

In some cases in which the contextual actions provide common action items, you might want to add a checkbox or a similar UI element that allows users to select items, because they might not discover the long-click behavior. When a user selects the checkbox, you can invoke the contextual action mode by setting the respective list item to the checked state with setItemChecked().

 

在上下文相关动作提供通用动作条目的一些情况中,你可能希望添加一个复选框或允许用户选择条目的一个类似的用户界面元素,因为他们可能没有发现长点击行为。当一个用户选择复选框时,你可以通过用setItemChecked()设置相应的列表条目为可勾选状态来调用上下文相关动作模式。

 

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

 

Creating a Popup Menu

 

创建一个弹出菜单

 

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

 

(图略:

动作栏下方右上角对齐的菜单,有两项:

* 回复全部

* 向前

 

Figure 4. A popup menu in the Gmail app, anchored to the overflow button at the top-right.

 

图4. 在Gmail应用中的一个弹出菜单,固定到右上角的溢出按钮。

 

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

 

A PopupMenu is a modal menu anchored to a View. It appears below the anchor view if there is room, or above the view otherwise. It's useful for:

 

一个PopupMenu是固定到一个View的一个模态菜单。它在固定视图的下方如果有空间的话,否则在视图的上方。它有用在:

 

* Providing an overflow-style menu for actions that relate to specific content (such as Gmail's email headers, shown in figure 4).

 

* 提供用于与特定内容相关的动作的一个溢出风格的菜单(诸如Gmail的电子邮件头部,如图4所示)。

 

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

 

Note: This is not the same as a context menu, which is generally for actions that affect selected content. For actions that affect selected content, use the contextual action mode or floating context menu.

 

注意:这不同于一个上下文菜单,上下文菜单通常用于影响被选择内容的动作。对于影响被选择内容的动作,请使用上下文相关动作模式或浮动上下文菜单。

 

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

 

* Providing a second part of a command sentence (such as a button marked "Add" that produces a popup menu with different "Add" options).

 

* 提供一个命令语句的第二部分(诸如一个标为“添加”的按钮产生一个带有不同“添加”选项的弹出菜单。

 

* Providing a drop-down similar to Spinner that does not retain a persistent selection.

 

* 提供一个类似于Spinner的下拉,它不维持一个持久的选择。

 

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

 

Note: PopupMenu is available with API level 11 and higher.

 

注意:PopupMenu在API级别11和更高版本中可用。

 

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

 

If you define your menu in XML, here's how you can show the popup menu:

 

如果你在XML中定义你的菜单,那么这里讲你如何显示弹出菜单:

 

1. Instantate a PopupMenu with its constructor, which takes the current application Context and the View to which the menu should be anchored.

 

1. 用它的构造函数实例化一个PopupMenu,它传入当前应用程序的Context和菜单应该固定到的View。

 

2. Use MenuInflater to inflate your menu resource into the Menu object returned by PopupMenu.getMenu(). On API level 14 and above, you can use PopupMenu.inflate() instead.

 

2. 使用MenuInflater来把你的菜单资源解压进PopupMenu.getMenu()返回的Menu对象。在API级别14和更高版本中,你可以改为使用PopupMenu.inflate()。

 

3. Call PopupMenu.show().

 

3. 调用PopupMenu.show()。

 

For example, here's a button with the android:onClick attribute that shows a popup menu:

 

例如,这里有一个带有android:onClick属性的按钮,它显示一个弹出菜单:

 

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

 

<ImageButton

    android:layout_width="wrap_content" 

    android:layout_height="wrap_content" 

    android:src="@drawable/ic_overflow_holo_dark"

    android:contentDescription="@string/descr_overflow_button"

    android:onClick="showPopup" />

 

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

 

The activity can then show the popup menu like this:

 

然后活动可以显示弹出菜单像这样:

 

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

 

public void showPopup(View v) {

    PopupMenu popup = new PopupMenu(this, v);

    MenuInflater inflater = popup.getMenuInflater();

    inflater.inflate(R.menu.actions, popup.getMenu());

    popup.show();

}

 

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

 

In API level 14 and higher, you can combine the two lines that inflate the menu with PopupMenu.inflate().

 

在API级别14和更高版本中,你可以用PopupMenu.inflate()组合压缩菜单的两行代码。

 

The menu is dismissed when the user selects an item or touches outside the menu area. You can listen for the dismiss event using PopupMenu.OnDismissListener.

 

当用户选中一个条目或触碰菜单区域外时菜单被解除。你可以使用PopupMenu.OnDismissListener监听解除事件。

 

Handling click events

 

处理点击事件

 

To perform an action when the user selects a menu item, you must implement the PopupMenu.OnMenuItemClickListener interface and register it with your PopupMenu by calling setOnMenuItemclickListener(). When the user selects an item, the system calls the onMenuItemClick() callback in your interface.

 

为了在用户选中一个菜单条目时执行一个动作,你必须实现PopupMenu.OnMenuItemClickListener接口并用你的PopupMenu通过调用setOnMenuItemclickListener()来注册它。当用户选中一个条目时,系统调用你的接口中的onMenuItemClick()回调。

 

For example:

 

例如:

 

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

 

public void showMenu(View v) {

    PopupMenu popup = new PopupMenu(this, v);

 

    // This activity implements OnMenuItemClickListener

    // 这个活动实现OnMenuItemClickListener

    popup.setOnMenuItemClickListener(this);

    popup.inflate(R.menu.actions);

    popup.show();

}

 

@Override

public boolean onMenuItemClick(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.archive:

            archive(item);

            return true;

        case R.id.delete:

            delete(item);

            return true;

        default:

            return false;

    }

}

 

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

 

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

 

Creating 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/menu_save"

          android:icon="@drawable/menu_save"

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

    <!-- menu group -->

    <!-- 菜单组 -->

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

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

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

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

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

    </group>

</menu>

 

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

 

The items that are in the group appear at the same level as the first item—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. The system will also never separate grouped items. For example, if you declare android:showAsAction="ifRoom" for each item, they will either both appear in the action bar or both appear in the action overflow.

 

在分组中的条目出现在同一层作为第一个条目——菜单中所有三个条目是平行的。然而,你可以通过引用组ID和使用上面列举的方法来修改分组中两个条目的特征。系统还将从不分开被分组的条目。例如,如果你对每个元素声明android:showAsAction="ifRoom",那么它们将都出现在动作栏中或都出现在动作溢出中。

 

Using checkable menu items

 

使用可勾选菜单条目

 

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

 

(图略:

地图模式:

* 地图 单选选中

* 卫星

* 交通

 

Figure 5. Screenshot of a submenu with checkable items.

 

图5. 一个带可勾选条目的子菜单的截屏。

 

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

 

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 5 shows a submenu with items that are checkable with radio buttons.

 

一个菜单可以是有用的作为一个界面用于开关一些选项,把一个复选框用于独立的选项,或者单选按钮用于互斥选项的分组。图5展示一个子菜单,它的条目是带单选按钮的可勾选条目。

 

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

 

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.

 

注意:可勾选菜单条目倾向于只被用在一个单会话的基础上,而且在应用程序销毁后不被保存。如果你有你想为用户保存的应用程序设置,你应该使用共享预设来存储数据。

 

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

 

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

 

Adding Menu Items Based on an Intent

 

基于一个意图添加菜单条目

 

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以启动一个活动(不管它是你的应用程序还是另一个应用程序的一个活动)。当你知道你希望使用的意图并且有一个应该初始化意图的特定菜单条目,你可以在合适的条目被选择的回调方法期间用startActivity()执行意图(诸如onOptionsItemSelected()回调)。

 

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()里创建一个Menu时它才应该被使用。

 

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

 

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 描述我们需求的在上面已经被创建的意图

         0,      // Additional flags to control items (none) 用来控制条目的附加标志(无)

         null);  // Array of MenuItems that correlate to specific items (none) 关联特定条目的MenuItems数组(无)

 

    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="@string/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 - 01 Feb 2012 20:50

 

Android 4.0 r1 - 06 Mar 2012 0:58 

 

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

patch:

1. Android 4.0 r1 - 06 Mar 2012 0:58 

* Using the contextual action bar

->

* Using the contextual action mode

 

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

 

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来源许可证描述的条款进行修改)

 

(本人翻译质量欠佳,请以官方最新内容为准,或者参考其它翻译版本:

* ソフトウェア技術ドキュメントを勝手に翻訳

http://www.techdoctranslator.com/android

* Ley's Blog

http://leybreeze.com/blog/

* 农民伯伯

http://www.cnblogs.com/over140/

* Android中文翻译组

http://androidbox.sinaapp.com/


分享到:
评论

相关推荐

    RealPlayer v18.1.15.215 官方英文版.zip

    浏览器在播放在线媒体视频的时候,鼠标浮向视频后会在其顶部出现Download This Video的按钮,能够一键快速保存视频到本地硬盘,或者选择下拉菜单进行控制。同时RealPlayer还设有下载和刻录管理器来方便用户管理。...

    超级笔画输入法(单手15简体) v6.2.3.zip

    显示汉字的解释和英文翻译,可以当作字典词典使用,适合儿童、小学生、外国人学习汉字文化。另外,还可以帮大家解决因为长期使用电脑打字而造成的“提笔忘字”毛病。   超级笔画输入法使用方法: 用超级笔画...

    15秋北交《计算机应用基础》在线作业二满分答案.pdf

    翻译程序 B. 应用程序 C. 晶体管 D. 操作系统 正确答案 :D 6. 在Word中,将一页分成两页,应选择的命令是( ) A. 格式菜单中的字体; B. 插入菜单中的页码 C. 插入菜单中的分隔符 D. 插入菜单中的自动图文集 正确...

    JeeWx 捷微微信管家平台 v4.1.zip

    15, 刮刮乐 16, 天气 17, 翻译 18, 微相册 19, 扩展接口 20, 微网站 JeeWx 捷微微信管家平台 v4.1更新日志 新增活动:微信新年砍价; 提供全新录制教学视频; 提供最新的使用文档; 修改域名变更,属性...

    JeeWx 捷微微信管家平台 v4.1

    1, 微信接口认证2, 菜单自定义3, 文本管理和回复4, 关注欢迎语5, 关键字管理6, 文本模板管理7, 图文模板管理8, 微信账号管理9, 用户管理10,角色管理11,菜单管理12, 支持多公众号13, 微网站14, 大转盘15,...

    ESM_ArcSight控制台用户指南(中文翻译版—Zephyr)_6.11.0 .pdf

    自定义活动列表的默认选择 15 设置日期和时间格式 16 设置纬度和经度选项 16 配置事件图 17 设置通知弹出窗口 19 管理热键 19 为常用资源添加快捷方式 20 修改自定义快捷方式 22 删除自定义快捷方式 24 激活新的快捷...

    IE 助手

    IE 助手是用Visual C++编写的一个能够随Internet Explorer自行启动的插件,它具有以下功能: 1.广告窗口拦截功能 IE 助手会尽可能拦截... 15.网页阅读  能够以中英文方式阅读网页选中文本和剪贴板中的内容.

    JAVA微信开发资料

    微信公众帐号开发教程第 15 篇-自定义菜单的 view 类型(访问网页).. 117 微信公众帐号开发教程第 16 篇-应用实例之历史上的今天.123 微信公众帐号开发教程第 17 篇-应用实例之智能翻译132 微信公众帐号开发教程第 ...

    Wicket 8.X开发文档(中文翻译+英文原版)

    页眉,页脚,左侧菜单,内容等... 5.2。这是继承! 5.3。划分et impera! 5.4。使用wicket标记继承:扩展标记 5.5。摘要 6.保持对HTML的控制 6.1。隐藏或禁用组件 6.2。修改标签属性 6.3。生成标记属性“id” 6.4。...

    Windows程序设计(第5版 珍藏版)清华版 1-4

    第10章 菜单和其他资源 333 第11章 对话框 385 程序 444 第12章 剪贴板 447 第II部分 关于图的那些事儿 第13章 使用打印机 471 第14章 位图和位块传输 505 第15章 设备无关位图 569 第16章 调色板管理器 643 第17...

    RSS聚合器「The RSS Aggregator」-crx插件

    日语翻译-葡萄牙语翻译-意大利语翻译-克罗地亚语翻译-韩语翻译-匈牙利语翻译4.7(05/04/14)-退格删除项目(适用于Mac用户)-土耳其语翻译-斯洛伐克语翻译4.5(23/02/14)-德语翻译3.7(15/01/14)在“高级”菜单项...

    微信公众平台开发最佳实践 源码及书箱

    2.1.4 上传代码 15 2.2 虚拟主机 18 第3章 开发模式 21 3.1 启用开发模式 21 3.1.1 关闭编辑模式 21 3.1.2 启用开发模式 22 3.1.3 常见问题与解决方案 23 3.2 实现自动回复 24 3.3 消息交互原理分析 24 第4...

    微信公众平台开发最佳实践 源代码

    2.1.4 上传代码 15 2.2 虚拟主机 18 第3章 开发模式 21 3.1 启用开发模式 21 3.1.1 关闭编辑模式 21 3.1.2 启用开发模式 22 3.1.3 常见问题与解决方案 23 3.2 实现自动回复 24 3.3 消息交互原理分析 24 第4...

    精通ANDROID 3(中文版)1/2

    第15章 闹钟管理器  15.1 闹钟管理器基本知识:设置一个简单的闹钟  15.1.1 获取闹钟管理器  15.1.2 设置闹钟时间  15.1.3 设置闹钟接收程序  15.1.4 创建适合闹钟的PendingIntent  15.1.5 设置闹钟  ...

    精通Android 3 (中文版)2/2

    第15章 闹钟管理器  15.1 闹钟管理器基本知识:设置一个简单的闹钟  15.1.1 获取闹钟管理器  15.1.2 设置闹钟时间  15.1.3 设置闹钟接收程序  15.1.4 创建适合闹钟的PendingIntent  15.1.5 设置闹钟  ...

    LabVIEW错误代码表

    表6 公式翻译器(Formula Parsing)错误代码表 13 表7 数学(Mathematics)错误代码表 14 表8 信号分析工具包(Signal Processing Toolset)错误代码表 17 表9 信号分析(Signal Processing)错误代码表 19 表10 逐...

    google改变生活

    8.1.2 菜单栏160 8.1.3 建立新的文件夹.161 8.2 在线文档——制作精美简历162 8.2.1 在线文档简介162 8.2.2 创建新的文档163 8.2.3 对文档进行布局.164 8.2.4 输入内容并排版.164 8.3 编辑演示文稿167 8.3.1 演示...

    1105741847整合脚本(RMXP)

    20·价格变动 翻译:柳柳 21·菜单显示血条 22·物品分类 可以自定义设置物品分类,利用物品描述,每个描述后面添加@物品分类即可。 23·任务和菜单 by 柳柳 24·完美输入法(具体看脚本里的长篇说明) 25·显示敌人...

    C++MFC教程

    尽量买翻译的书,因为这些书一般都比较易懂,而且语言比较轻松。买书前一定要慎重如果买到不好用的书可能会对自己的学习积极性产生击。 对于已经掌握了VC的朋友:这种程度的开发者应该加深自己对系统原理,技术...

Global site tag (gtag.js) - Google Analytics