Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 416
Noor Avatar asked Mar 28 '14 06:03

Noor


2 Answers

You could try

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

As mentioned here

like image 122
nicja Avatar answered Sep 21 '22 12:09

nicja


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.

like image 28
Keya Avatar answered Sep 19 '22 12:09

Keya