Reputation: 1078
I need to get a reference to an item in my actionbar. I want to access it in 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));
}
Any ideas?
Upvotes: 0
Views: 120
Reputation: 1078
do the work in onCreateOptionsMenu()
instead, then it will be accessable:
@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;
}
Upvotes: 0
Reputation: 1360
In onCreateOptionsMenu(Menu menu)
store the reference of the menu in a class-level variable. Like this:
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));
}
}
Upvotes: 1