选择器不适用于带有矢量的复选框

Selector doesn't work on Checkbox with vectors

所以,我过去做过选择器,但我不知道为什么这次不起作用。我有 2 个矢量可绘制对象,计划在单击时在它们之间切换。 我创建了以下选择器文件:

 <?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>

这是我的复选框:

<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"/>

但是,每当我点击它时,什么都没有改变。我试过 android:checked="true" 但还是一样。

您只需从选择器中删除 android:state_selected="true"。应该只是

<?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> 

将此添加到您的模块级别 build.gradle

 vectorDrawables.useSupportLibrary = true

将此添加到您的 Activity/Fragment

 static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

从 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"/>

像这样以编程方式设置 CheckBox 自定义可绘制对象

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

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

使用这个属性

app:useMaterialThemeColors="false"