03 September 2016

Android Favourite Star


So I recently needed a favourite button and I thought Android's classic star button would fit the bill quite nicely. So I found this stack overflow page which sounded like just what I needed:

http://stackoverflow.com/questions/8244252/star-button-in-android

I create my ImageView and set the src to @android:drawable/btn_star

However I came across one big problem, I couldn't for the life of me get the on state to stick. I tried setSelected but nothing happened. I looked at the drawable in the Android package and it seemed what I was really looking for was setChecked, but an ImageView doesn't have a checked state. Nor does a Button, nor a ImageButton and a CheckBox doesn't have a src. So I was stumped.

After some time I found what I needed

        <CheckBox
            android:id="@+id/item_star"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/favourite"
            android:duplicateParentState="true"
            android:button="@android:drawable/btn_star" />


I used a checkbox with a button value set to the Android drawable. Hope it helps :)