您可以通过应用栏添加用户操作按钮。借助此功能,您可以将当前上下文中最重要的操作放在应用顶部。例如,当用户查看相册时,照片浏览应用可以在顶部显示分享和创建 影集按钮。当 用户查看单张照片时,此应用可以显示剪裁按钮和 滤镜按钮。
应用栏中的空间有限。如果应用声明的操作数量过多,导致应用栏无法容纳,则应用栏会将无法容纳的操作发送到“溢出”菜单。 应用还可以指定某项操作始终显示在溢出菜单中,而不是显示在应用栏中。
添加操作按钮
操作溢出中提供的所有操作按钮和其他项都在 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 图标中找到许多有用的图标。
响应操作
当用户选择某个应用栏项时,系统会调用 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); } }