Wednesday, April 14, 2010

How-to: Android Favorite Button (the right way, this time)

My last blog post is about how to make a favorite button in an Android application. It is wrong, those drawables should not be used independently. Instead, the @android:drawable/btn_star resource should be used, as it is a state-drawable and contains all the possible states (checked, unchecked, checked and focused, checked and clicked, ...). The proper way to use this is:

<CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:button="@android:drawable/btn_star"/>

The result looks exactly like the button used in Android's Contacts application when viewing a contact (upper-right corner).

Man, that took some digging.

6 comments:

  1. Thank you. Exactly what I've been looking for - I've figured out the whole state thing but I've been setting android:background instead of android:button and ended up with 2 buttons instead. Now it all works well.

    ReplyDelete
  2. haha me too artem, thanks felix

    ReplyDelete
  3. Amazing! Just what I need! :)

    ReplyDelete
  4. This worked perfectly to change the checkbox to a different android image. But if you want to change the default checkbox to a custom image:

    Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' images to your custom ones.

    The last change is then android:button="@drawable/btn_check" rather than android:button="@android:drawable/btn_check"

    ReplyDelete
  5. Thank you

    Regards,
    Vivek Kumar

    ReplyDelete
  6. thank you felix. this is awesome. i just removed 20 lines of messy code thanks to you.

    ReplyDelete