jlively
jlively

Reputation: 743

Selector doesn't work on Checkbox with vectors

So, I've done selectors in the past and I have no idea why it doesn't work this time. I have 2 vector drawables and the plan is to change between them on click. I've created the following selector file:

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

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

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

And this is my checkbox:

<CheckBox
            android:id="@+id/checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/ic_phone_margin"
            android:button="@drawable/ic_favorite_selector"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/iv_call"
            app:layout_constraintTop_toTopOf="parent"/>

But, whenever I click it, nothing changes. I've tried with android:checked="true" but it's still the same.

Upvotes: 1

Views: 662

Answers (3)

Camel
Camel

Reputation: 151

Use this attribute

app:useMaterialThemeColors="false"

Upvotes: 2

Mansukh Ahir
Mansukh Ahir

Reputation: 3563

Add this in your module-level build.gradle

 vectorDrawables.useSupportLibrary = true

Add this in your Activity/Fragment

 static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

Remove Vector drawable from XML

<CheckBox
            android:id="@+id/checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/ic_phone_margin"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/iv_call"
            app:layout_constraintTop_toTopOf="parent"/>

Set CheckBox custom drawable programmaticully like this

CheckBox cb = findViewById(R.id.checkBox);

cb.setButtonDrawable(AppCompatResources.getDrawable(getContext(), R.drawable.ic_favorite_selector));

Upvotes: 0

Napster
Napster

Reputation: 1383

You just need to remove android:state_selected="true" from your selector. It should just be

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

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

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

Upvotes: 1

Related Questions