添加和处理操作

尝试 Compose 方式
Jetpack Compose 是推荐的 Android UI 工具包。了解如何在 Compose 中添加组件。

应用栏可让您添加用户操作按钮。此功能可让您将当前上下文中最重要的操作放置在应用的顶部。例如,照片浏览应用在用户查看照片列表时可能会在顶部显示分享创建相册按钮。当用户查看单张照片时,应用可能会显示裁剪滤镜按钮。

应用栏空间有限。如果应用声明的操作多于应用栏可容纳的数量,应用栏会将多余的操作发送到溢出菜单。应用还可以指定某个操作始终显示在溢出菜单中,而不是显示在应用栏上。

An image showing Now in Android app with a action bar icon
图 1. “Now in Android”应用中的操作图标。

添加操作按钮

所有操作按钮以及操作溢出菜单中的其他项目都在 XML 菜单资源中定义。要向操作栏添加操作,请在项目的 res/menu/ 目录中创建新的 XML 文件。

为要包含在操作栏中的每个项目添加 <item> 元素,如下面的示例菜单 XML 文件所示:

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

    <!-- "Mark Favorite", must appear as action button if possible. -->
    <item
        android:id="@+id/action_favorite"
        android:icon="@drawable/ic_favorite_black_48dp"
        android:title="@string/action_favorite"
        app:showAsAction="ifRoom"/>

    <!-- Settings, must always be in the overflow. -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          app:showAsAction="never"/>

</menu>

app:showAsAction 属性指定操作是否在应用栏上显示为按钮。如果您设置 app:showAsAction="ifRoom"(例如示例代码中的收藏夹操作),则如果应用栏中有足够的空间,该操作将显示为按钮。如果空间不足,多余的操作将发送到溢出菜单。如果您设置 app:showAsAction="never"(例如示例代码中的设置操作),则该操作始终在溢出菜单中列出,而不会显示在应用栏中。

如果操作显示在应用栏中,系统会使用该操作的图标作为操作按钮。您可以在 Material Icons 中找到许多有用的图标。

响应操作

当用户选择应用栏中的某个项目时,系统会调用您 Activity 的 onOptionsItemSelected() 回调方法,并传递一个 MenuItem 对象以指示哪个项目被点按。在您的 onOptionsItemSelected() 实现中,调用 MenuItem.getItemId() 方法以确定哪个项目被点按。返回的 ID 与您在相应 <item> 元素的 android:id 属性中声明的值匹配。

例如,以下代码段检查用户选择的操作。如果方法无法识别用户的操作,它将调用超类方法:

Kotlin

override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
    R.id.action_settings -> {
        // User chooses the "Settings" item. Show the app settings UI.
        true
    }

    R.id.action_favorite -> {
        // User chooses the "Favorite" action. Mark the current item as a
        // favorite.
        true
    }

    else -> {
        // The user's action isn't recognized.
        // Invoke the superclass to handle it.
        super.onOptionsItemSelected(item)
    }
}

Java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            // User chooses the "Settings" item. Show the app settings UI.
            return true;

        case R.id.action_favorite:
            // User chooses the "Favorite" action. Mark the current item as a
            // favorite.
            return true;

        default:
            // The user's action isn't recognized.
            // Invoke the superclass to handle it.
            return super.onOptionsItemSelected(item);

    }
}