Android 可检查菜单项

问题描述:

我的 Android 应用中有以下菜单布局:

I have the following menu layout in my Android app:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/item1" 
          android:titleCondensed="Options"
          android:title="Highlight Options" 
          android:icon="@android:drawable/ic_menu_preferences" />

   <item android:id="@+id/item2" 
         android:titleCondensed="Persist"
         android:title="Persist" 
         android:icon="@android:drawable/ic_menu_preferences" 
         android:checkable="true" />
</menu>

我的问题是,当我在 Android 模拟器中运行我的应用程序时,第二个菜单项似乎不是可检查的".该项目应该有一个绿色的勾,对吗?表示其可检查.

My problem is that the second menu item doesn't appear to be "checkable" when I run my app in the Android emulator. There should be a green tick about the item, right? To indicate that its checkable.

我做错了吗?

布局看起来不错.但是您必须在代码中选中和取消选中菜单项.

Layout looks right. But you must check and uncheck menu item in code.

来自文档:

当一个checkable item被选中时,系统会调用你各自的item-selected回调方法(比如onOptionsItemSelected()).您必须在此处设置复选框的状态,因为复选框或单选按钮不会自动更改其状态.您可以使用 isChecked() 然后使用 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().