I got a sub-menu that I add with values, I then want to set them up by reading the currentViewMode variable that contain the current view mode… The code below must check the first one but it doesn’t. Please advise.
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;
}
You should make the checkbox updates in onPrepareOptionsMenu (instead of onCreateOptionsMenu), as it will be invoked on every menu open.
Create only called before the very first.
(its not sure if this is causing your problem, but is possible, so worth a try, and makes your code safer, anyway)