我有一个子菜单,在xml中设置按钮,工作正常。
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Single menu item
Set id, icon and Title for each menu item
-->
<item android:id="@+id/menu_level"
android:title="Set Level" >
<menu>
<group android:checkableBehavior="single">
<item android:id="@+id/one"
android:checked="false"
android:title="One" />
<item android:id="@+id/two"
android:title="Two" />
<item android:id="@+id/three"
android:title="Three" />
</group>
</menu>
</item>
<item android:id="@+id/menu_save"
android:icon="@drawable/icon_save"
android:title="Save" />
<item android:id="@+id/menu_about"
android:icon="@drawable/icon_bookmark"
android:title="About">
<menu>
<item android:id="@+id/copyright"
android:title="(c) John Beukema 2012">
</item>
</menu>
<item/>
</menu>
我按如下方式访问它:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Editor editor = PreferenceManager
.getDefaultSharedPreferences(this).edit();
switch (item.getItemId())
{
case R.id.menu_save:
return true;
case R.id.menu_recall:
return true;
case R.id.menu_level: {
return true;
}
case R.id.menu_about:
return true;
case R.id.one:
star = 1;
editor.putInt("Star", 1);
editor.commit();
item.setChecked(true);
return true;
case R.id.two:
star = 2;
editor.putInt("Star", 2);
editor.commit();
item.setChecked(true);
return true;
case R.id.three:
star = 3;
editor.putInt("Star", 3);
editor.commit();
item.setChecked(true);
return true;
case R.id.menu_delete:
return true;
case R.id.menu_preferences:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
到目前为止没问题。但是我想从首选项启动时加载按钮。
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
star = preferences.getInt("Star", 1);
MenuItem one = (MenuItem) findViewById(R.id.one);
MenuItem two = (MenuItem ) findViewById(R.id.two);
MenuItem three = (MenuItem) findViewById(R.id.three);
switch(star)
{
case 1:
one.setChecked(true); break;
case 2:
two.setChecked(true); break;
case 3:
three.setChecked(true); break
}
}
}
这编译但挂起。如何处理子菜单按钮?
答案 0 :(得分:1)
我认为你不能在menuitem上做findviewbyid。您需要在onprepareoptionsmenu
中设置或取消设置选中的项目