问题描述
我以这种方式定义了 MenuItem:
I have MenuItem defined this way:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_starred"
android:icon="@drawable/btn_star"
android:title="@string/description_star"
android:checkable="true"
android:checked="true"
android:orderInCategory="1"
android:showAsAction="always" />
</menu>
和btn_star.xml
是这样定义的:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="false"
android:drawable="@drawable/btn_star_off_normal" />
<item
android:state_checked="true"
android:drawable="@drawable/btn_star_on_normal" />
</selector>
然而,当我使用它创建选项菜单时,即使 MenuItem
的 isChecked()
属性为真,图标也永远不会显示为选中状态.
When I create an options menu using this, however, the icon is never shown in its checked state, even if the MenuItem
's isChecked()
property is true.
我正在使用 ActionBarSherlock 控件,但是,如果我只是创建一个普通选项,我会得到相同的结果菜单并调用 setChecked(true)
.无论项目的选中状态如何,它仍然显示 btn_star_off
drawable.
I'm using the ActionBarSherlock control, however, I'm getting the same result if I simply create a normal options menu and call setChecked(true)
. It still displays the btn_star_off
drawable regardless of the checked state of the item.
onOptionsItemSelected()
方法被正确调用,我可以成功更改checked 属性:
The onOptionsItemSelected()
method is being called correctly, and I can successfully change the checked property:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.isCheckable()) {
item.setChecked(!item.isChecked());
}
return super.onOptionsItemSelected(item);
}
在此处设置断点显示 isChecked 属性正在更改,但图标本身并未更新以反映正确的状态.
Setting a breakpoint here shows the isChecked property being changed, but the icon itself is not updated to reflect the correct state.
我在这里遗漏了什么吗?我这样做不正确吗?我不明白为什么这不能正常工作.
Is there something I'm missing here? Am I doing this incorrectly? I can't figure out why this wouldn't be working correctly.
推荐答案
根据官方文档 http://developer.android.com/guide/topics/ui/menus.html
注意:图标菜单(来自选项菜单)中的菜单项不能显示复选框或单选按钮.如果您选择在图标菜单可检查,您必须手动指示选中状态每次状态改变时交换图标和/或文本.
希望有帮助.
这篇关于MenuItem 的选中状态未通过其图标正确显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!