简体   繁体   中英

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;

  }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM