我得到了一个用值添加的子菜单,然后我想通过读取包含当前视图模式的currentViewMode变量来设置它们......下面的代码必须检查第一个,但它没有。请指教。
private enum ViewMode
{
NORMAL,
SATELLITE,
HYBRID
}
private ViewMode currentViewMode = ViewMode.NORMAL;
private final int SUB_MENU_GROUP = 1;
private final int SUB_MENU_ITEM_NORMAL = 1;
private final int SUB_MENU_ITEM_SATELLITE = 2;
private final int SUB_MENU_ITEM_HYBRID = 3;
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu sub = menu.addSubMenu(0, 1, 0, R.string.menu_mapwindow_viewmode).setIcon(R.drawable.ic_menu_refresh);
sub.add(SUB_MENU_GROUP, SUB_MENU_ITEM_NORMAL, Menu.NONE, this.getString(R.string.mapwindow_viewmode_normal));
sub.add(SUB_MENU_GROUP, SUB_MENU_ITEM_SATELLITE, Menu.NONE, this.getString(R.string.mapwindow_viewmode_satellite));
sub.add(SUB_MENU_GROUP, SUB_MENU_ITEM_HYBRID, Menu.NONE, this.getString(R.string.mapwindow_viewmode_hybrid));
sub.setGroupCheckable(SUB_MENU_GROUP, true, true);
if (this.currentViewMode == ViewMode.NORMAL)
sub.findItem(SUB_MENU_ITEM_NORMAL).setChecked(true);
else if (this.currentViewMode == ViewMode.SATELLITE)
sub.findItem(SUB_MENU_ITEM_SATELLITE).setChecked(true);
else if (this.currentViewMode == ViewMode.HYBRID)
sub.findItem(SUB_MENU_ITEM_HYBRID).setChecked(true);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case SUB_MENU_ITEM_NORMAL:
item.setChecked(!item.isChecked());
this.currentViewMode = ViewMode.NORMAL;
Log.i(this.getClass().getName(), "Normal");
break;
case SUB_MENU_ITEM_SATELLITE:
item.setChecked(!item.isChecked());
this.currentViewMode = ViewMode.SATELLITE;
Log.i(this.getClass().getName(), "Satellite");
break;
case SUB_MENU_ITEM_HYBRID:
item.setChecked(!item.isChecked());
this.currentViewMode = ViewMode.HYBRID;
Log.i(this.getClass().getName(), "Hybrid");
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
答案 0 :(得分:0)
您应该在onPrepareOptionsMenu(而不是onCreateOptionsMenu)中进行复选框更新,因为它将在每个打开的菜单上调用。 创建仅在第一个之前调用。 (它不确定这是否会导致您的问题,但是可能,所以值得一试,并且无论如何都会使您的代码更安全)