6

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

Noor
  • 19,638
  • 38
  • 136
  • 254
  • use shared pref. for remember bookmark has been pressed before or not according to it change your drawable – MilapTank Mar 28 '14 at 06:52
  • yes, this was the second option i would chose, so, is it not possible to get the drawble from the menu item – Noor Mar 28 '14 at 06:54
  • but no need to store drawable into shared pref. store Boolean that is pressed or not and change according to it – MilapTank Mar 28 '14 at 06:58

3 Answers3

14

You could try

if (item.getIcon().getConstantState().equals(
        getResources().getDrawable(R.drawable.starto).getConstantState()
)) {
    ...
}

As mentioned here

Community
  • 1
  • 1
nicja
  • 574
  • 5
  • 21
1

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.

Keya
  • 859
  • 3
  • 9
  • 17
0

you can compare these too.

you can find id of drawable by

int identifier = getResources().getIdentifier("pic1", "drawable","android.demo");

and then you can compare this with R.drawable.starto `.

Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45