Reputation: 14122
I have a checkable MenuItem
in my application. I check for the last state and change its icon according to the pervious state (when app restarts or ...). The problem is, when the device orientation changes, these methods that I have below does not work!
I wonder if it is my code or there is a special case when orientation changes and the menu items get reset?
It is defined in the xml file like so:
So the above is the default behavior that I want, that is when the application installs on the phone it's first statee should be false
.
In the activity, I have in onPrepareOptionsMenu
the following code, which will check the state and changes the icon before showing the menu to user:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.action_toggle_logging);
if (item.isChecked()) {
item.setIcon(R.drawable.ic_action_stop);
} else {
item.setIcon(R.drawable.ic_action_play);
}
return true;
}
And here is in the onOptionsItemSelected
method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_toggle_logging:
if (item.isChecked()) {
getApplicationReference().stopLoggerService(); //stop stuff
item.setIcon(R.drawable.ic_action_play);
} else {
getApplicationReference().startLoggerService(); //start stuff
item.setIcon(R.drawable.ic_action_stop);
}
item.setChecked(!item.isChecked());
}
return super.onOptionsItemSelected(item);
}
Upvotes: 0
Views: 547
Reputation: 17820
You can persist local members to a bundle. This lets them survive configuration changes (like orientation changes).
private static final String LOGGGING_KEY = "logging-key";
private boolean mLoggingOn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mLoggingOn = savedInstanceState.getBoolean(LOGGGING_KEY, false);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(LOGGGING_KEY, mLoggingOn);
super.onSaveInstanceState(outState);
}
Upvotes: 1