添加和处理操作

您可以通过应用栏添加用户操作按钮。借助此功能,您可以将当前上下文中最重要的操作放在应用顶部。例如,当用户查看相册时,照片浏览应用可以在顶部显示“分享”按钮和“创建影集”按钮;当用户查看单张照片时,此应用可以显示“剪裁”按钮和“滤镜”按钮。

应用栏中的空间有限。如果应用声明的操作数量过多,导致应用栏无法容纳,则应用栏会将无法容纳的操作发送到“溢出”菜单。应用还可以指定某项操作应始终显示在溢出菜单中,而不是显示在应用栏中。

图 1. 包含单个操作按钮和溢出菜单的应用栏。

添加操作按钮

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

为要添加到操作栏中的每项内容分别添加一个 <item> 元素,如以下菜单 XML 文件代码示例中所示:

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

        <!-- "Mark Favorite", should 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, should 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 图标页面找到许多有用的图标。

响应操作

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

例如,以下代码可以检查用户选择的是哪项操作。 如果此方法无法识别用户的操作,则会调用父类方法:

Kotlin

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

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

        else -> {
            // If we got here, the user's action was not 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 chose the "Settings" item, show the app settings UI...
                return true;

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

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }