Marton_HUN
Marton_HUN

Reputation: 43

Android ActionBar - Item icon change continuously?

On my ActionBar there is one item that has an icon about a star(without filled). When the user clicks on it, the icon changes to another icon(filled star). But the problem is that if the user cliccks again the icon doesn't change one more time.

So, this is what i want

icon1->click->icon2->click->icon1->click->icon2

My item xml:

<item
    android:id="@+id/bookmark"
    android:icon="@drawable/bookmark"
    android:showAsAction="ifRoom"
    android:title="Add to Favorites"/>

My Java for actionBar:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.activity_desc, menu);
}



@Override
  public boolean onOptionsItemSelected(MenuItem item) {

    if(item.getItemId() == R.id.bookmark){



        // i tried this: something like: if(item.getIcon() == (R.drawable.nobookmark){} it doesn't work 


        item.setIcon(R.drawable.nobookmark);

        return true;
    }

    return true;

  }

Upvotes: 2

Views: 2726

Answers (1)

weston
weston

Reputation: 54781

In your item.xml make it checkable:

<item
    android:id="@+id/bookmark"
    android:icon="@drawable/nobookmark"
    android:checkable="true"
    android:showAsAction="ifRoom"
    android:title="Add to Favorites"/>

In the java you must manually toggle the checked state and select the icon:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  if(item.getItemId() == R.id.bookmark){
    item.setChecked(!item.isChecked());
    item.setIcon(item.isChecked() ? R.drawable.bookmark : R.drawable.nobookmark);
    return true;
  }
  return false;
}

Upvotes: 6

Related Questions