Noor
Noor

Reputation: 20150

get drawable from Android Menu Item Icon

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

Upvotes: 6

Views: 7275

Answers (3)

Waqar Ahmed
Waqar Ahmed

Reputation: 5068

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 `.

Upvotes: 0

Keya
Keya

Reputation: 849

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.

Upvotes: 1

nicja
nicja

Reputation: 574

You could try

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

As mentioned here

Upvotes: 14

Related Questions