问题描述
我正试图隐藏一个MenuItem
并在选择第一个时使其他可见.
I'm trying to hide one MenuItem
and make another visible when the first is selected.
每个的ID为:
pencil: R.id.button_routines_edit
check mark: R.id.button_routines_edit_done
以下是相关代码:
private boolean isEditing = false;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.button_routines_edit:
// hide pencil icon, show checkmark
isEditing = true;
return true;
case R.id.button_routines_edit_done:
// show pencil icon, done editing
isEditing = false;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// hide pencil when editing and show check mark
menu.findItem(R.id.button_routines_edit).setVisible(!isEditing);
menu.findItem(R.id.button_routines_edit_done).setVisible(isEditing);
return true;
}
我的问题是:选择项目时,选项菜单"不会重新绘制它们.换句话说,第一个未隐藏,第二个未显示.
My problem is:The Options Menu doesn't redraw the items when they're selected. In other words, the first isn't hidden and the second isn't shown.
推荐答案
您需要做的就是调用invalidateOptionsMenu()
.
All you need to do is call invalidateOptionsMenu()
.
invalidateOptionsMenu()仅在API中可用11岁以上,除非您使用的是 ActionBarSherlock .
invalidateOptionsMenu() is only available in API 11+, unless you're using ActionBarSherlock.
您遇到了这个问题,因为您的MenuItems
基本上显示在ActionBar
中.如果将它们放在溢出菜单中,则无需调用invalidateOptionsMenu()
.
You're having this problem because your MenuItems
are show in the ActionBar
, basically. If you place them in the overflow menu, you won't need to call invalidateOptionsMenu()
.
这篇关于单击时更改MenuItem可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!