应用栏允许您添加用于用户操作的按钮。此功能使您可以将当前上下文中最重要 操作 放置在应用顶部。例如,照片浏览应用在用户查看照片库时,可能会在顶部显示 分享 和 创建相册 按钮。当用户查看单张照片时,应用可能会显示 裁剪 和 滤镜 按钮。
应用栏中的空间有限。如果应用声明的操作超过了应用栏所能容纳的数量,应用栏会将多余的操作发送到 溢出 菜单中。应用还可以指定某个操作始终显示在溢出菜单中,而不是显示在应用栏上。
添加操作按钮
操作溢出菜单中提供的所有操作按钮和其他项目都在 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); } }