我需要在操作栏中获取对项目的引用。我想在onCreate
int silent_mode = SupportFunctions.getSharedPreferenceInt(getApplicationContext(), getResources().getString(R.string.shared_preferences_name), "silent_mode", 0);
Item item = // getItem?
if (silent_mode == 1) {
item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_on));
}
else {
item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_off));
}
有什么想法吗?
答案 0 :(得分:1)
在onCreateOptionsMenu(Menu menu)
中将菜单的引用存储在类级变量中。像这样:
Menu mnMenu;
public boolean onCreateOptionsMenu(Menu menu) {
....
....
mnMenu = menu;
return true;
}
private void someMethod() {
int silent_mode = SupportFunctions.getSharedPreferenceInt(getApplicationContext(), getResources().getString(R.string.shared_preferences_name), "silent_mode", 0);
MenuItem item = mnMenu.findItem(R.id.action) //R.id.action is the id of your MenuItem
if (silent_mode == 1) {
item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_on));
}
else {
item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_off));
}
}
答案 1 :(得分:0)
在onCreateOptionsMenu()
中完成工作,然后它将是可访问的:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
...
MenuItem item = menu.findItem(R.id.YOUR_ID);
int silent_mode = SupportFunctions.getSharedPreferenceInt(getApplicationContext(), getResources().getString(R.string.shared_preferences_name), "silent_mode", 0);
if (silent_mode == 1) {
item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_on));
}
else {
item.setIcon(getResources().getDrawable(R.drawable.ic_silent_mode_off));
}
return true;
}