jeudi 7 octobre 2021

Change Checkbox background on click?

I have a Checkbox with custom images inside a selector...

and I am trying to achieve the following effect wnen the checkbox is clicked:

Gif for reference:

Tha background has to change while the checkbox is pressed and then goes back to normal when released.

The first two buttons are ImageButtons and the effect was easily achieved but with Checkbox I'm struggling. I guess it has to be something with the selector itself but I am not quite sure how to implement it. I tried adding a shape inside an item and a solid color but I couldn't make it work. Please point me in the right direction.

My checkbox code below (it uses two-way data binding):

 <CheckBox
    android:id="@+id/btn_addtofavs"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/inflated_selector_is_checked"
    android:button="@null"
    android:checked="@={inflatedItemViewModel.item.checked}"
    android:onClick="@{() -> inflatedItemViewModel.updateChecked(inflatedItemViewModel.item.id, inflatedItemViewModel.item.checked)}"
    tools:ignore="ContentDescription" />

My Checkbox selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/ic_inflated_star_outline"
        android:state_checked="false"/>

    <item
        android:drawable="@drawable/ic_inflated_star_full"
        android:state_checked="true"/>

    <item
        android:drawable="@drawable/ic_inflated_star_outline"/>

</selector>

Other 2 buttons selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/blue_200"/>
            <corners android:radius="@dimen/_8sdp"/>
        </shape>
    </item>

    <item android:state_pressed="false">
        <shape>
            <solid android:color="@color/blue_500"/>
            <corners android:radius="@dimen/_8sdp"/>
        </shape>
    </item>
</selector>

Thank you! ^^




Aucun commentaire:

Enregistrer un commentaire