如何在 android 中自定义 MaterialCheckBox?

How to customize MaterialCheckBox in android?

我想做一个圆形 MaterialCheckBox 它和圆形一样完美,但是圆形的颜色改变了,这不是我在 ic_checkedic_unchecked 中设置的颜色。这是我的代码。为什么这不选择矢量颜色

XML布局

 <com.google.android.material.checkbox.MaterialCheckBox
            android:id="@+id/selection_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:button="@drawable/custom_checkbox"
            />

drawable/custom_checkbox

<?xml version="1.0" encoding="utf-8"?>
<selector  xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true"
        android:drawable="@drawable/ic_checked"/>
    <item
        android:state_pressed="true"
        android:drawable="@drawable/ic_checked"/>
    <item
        android:state_pressed="false"
        android:drawable="@drawable/ic_unchecked"/>
</selector>

drawable/ic_checked

<vector android:height="20dp" android:tint="#F44336"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="20dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#ffffff" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z"/>
</vector>

drawable/ic_unchecked

<vector android:height="20dp" android:tint="#FFFFFF"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="20dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#FF000000" android:pathData="M12,2C6.47,2 2,6.47 2,12s4.47,10 10,10 10,-4.47 10,-10S17.53,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8z"/>
</vector>

The color of the checkbox defaults to ?attr/colorOnSurface (unchecked) and ?attr/colorSecondary (checked) defined in your app theme. If you want to override this behavior, as you might with a custom drawable that should not be tinted, set app:useMaterialThemeColors to false

尝试将此添加到您的复选框代码中:

app:useMaterialThemeColors="false"

如果这不起作用,那么使用这个:

您必须在复选框样式中设置按钮色调。 在color目录新建一个资源文件,命名为button_tint.

button_tint.xml : (设置你选择的颜色)

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#F44336" android:state_checked="true"/>
<item android:alpha="0.38" android:color="@color/white" android:state_enabled="false"/>
<item android:color="@color/white"/>
</selector>

现在在 theme.xml 添加:

<style name="Widget.App.CheckBox" parent="Widget.MaterialComponents.CompoundButton.CheckBox">
    <item name="buttonTint">@color/button_tint</item>
</style>

最后将此样式添加到您的复选框:

style="@style/Widget.App.CheckBox"

这将在复选框上应用您的自定义颜色。