I have a bookmark icon in a menu item. I want to change the drawable in the icon depending on whether the bookmark has been pressed before or not.
I have two drawbles, staro (meaning star orange) or starw(meaning star white). I just want to toggle this on press.
How can I know which drawble is in the icon in public boolean onOptionsItemSelected(MenuItem item)
method. Is it possible to know the drawable via the item. what I know is that item.getIcon() is not the drawble. I cannot compare item.getIcon()
with R.drawable.starto
You could try
if (item.getIcon().getConstantState().equals(
getResources().getDrawable(R.drawable.starto).getConstantState()
)) {
...
}
As mentioned here
You can do the changes in onPrepareOptionsMenu() which is called every time before the menu is shown. Its suitable to show/hide options based on some dynamic data.
If you already now the condition, you can directly call
if (condition_for_orange) {
menu.findItem(resourceId).setIcon(R.drawable.staro);
} else {
menu.findItem(resourceId).setIcon(R.drawable.startw);
}
You can use Shared Preference or some other global variable which can store the state which may help you to decide which icon to show now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With