Search code examples
androidcheckboxandroid-actionbar

Android- How to implement a "Like" button in ActionBar


I have to implement a "Like" button in the ActionBar of my Activity. I saw that Android does not support a CheckBox for a MenuItem and would have to change the icon manually. I'm trying to do it, but the picture doesn't change using setIcon.

Could anyone help me?

here is my XML:

<item android:id="@+id/action_good"
        android:title="@string/action_good"
        android:icon="@drawable/like"

        android:orderInCategory="100"
        app:showAsAction="ifRoom" />

And here is my code:

public boolean onOptionsItemSelected(MenuItem item) {


        switch (item.getItemId()) {
            case R.id.action_good:
               //Handle the action
                item.setIcon(R.drawable.like_selected);
                break:

Solution

  • You can use custom view instead of simple icon. You can set menu icon in onCreateOptionsMenu() only. So, if you don't wont implement custom view, you need to call invalidateOptionsMenu() all the time, to re-create all menu.