我如何改变默认的复选框的颜色在Android? 默认情况下,复选框的颜色是绿色,我想改变这个颜色。 如果不可能,请告诉我如何做一个自定义复选框?


当前回答

您可以使用单行代码更改复选框的颜色

android:buttonTint="@color/app_color" //任意颜色

其他回答

在你的styles.xml文件中添加这一行:

<style>
    <item name="android:colorAccent">@android:color/holo_green_dark</item>
</style>

我的minSdkVersion是15,我的BaseAppTheme父是Theme.AppCompat.Light.NoActionBar,我正在以编程方式创建我的复选框。下面的步骤对我很有效。

1. 在Java代码中进行更改

CheckBox checkBox = new CheckBox(context);

to

AppCompatCheckBox checkBox = new AppCompatCheckBox(context);

2. 在你的styles.xml中,添加:

<style name="MyCheckboxStyle" parent="Widget.AppCompat.CompoundButton.CheckBox">
    <item name="buttonTint">@color/primary_dark</item>
</style>

3.最后,在你的BaseAppTheme(或AppTheme)样式中,添加:

<item name="checkboxStyle">@style/MyCheckboxStyle</item>
<item name="android:checkboxStyle">@style/MyCheckboxStyle</item>

你可以创建自己的XML在drawable和使用这作为android:background="@drawable/your_xml"

这样你就可以给边角任何东西

<item>
    <shape>
        <gradient

            android:endColor="#fff"
            android:startColor="#fff"/>
        <corners
            android:radius="2dp"/>
        <stroke
            android:width="15dp"
            android:color="#0013669e"/>

    </shape>
</item>

我更喜欢我创建的这个扩展函数:

fun CheckBox.setTint(@ColorInt color: Int?) {
    if (color == null) {
        CompoundButtonCompat.setButtonTintList(this, null)
        return
    }
    CompoundButtonCompat.setButtonTintMode(this, Mode.SRC_ATOP)
    CompoundButtonCompat.setButtonTintList(this, ColorStateList.valueOf(color))
}

它非常类似于我的ImageView,以防有人也想要它:

fun ImageView.setTint(@ColorInt color: Int?) {
    if (color == null) {
        ImageViewCompat.setImageTintList(this, null)
        return
    }
    ImageViewCompat.setImageTintMode(this, Mode.SRC_ATOP)
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(color))
}

100%鲁棒方法。

在我的情况下,我没有访问XML布局源文件,因为我从第三方MaterialDialog库获得复选框。 所以我必须通过编程来解决这个问题。

在xml中创建ColorStateList:

res /颜色/ checkbox_tinit_dark_theme.xml:

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

然后应用到复选框: ColorStateList darkStateList = ContextCompat.getColorStateList(getContext(), R.color.checkbox_tint_dark_theme); CompoundButtonCompat。darkStateList setButtonTintList(复选框);

另外,如果有人感兴趣,下面是如何从MaterialDialog对话框中获得复选框(如果你设置了.checkBoxPromptRes(…)):

CheckBox checkbox = (CheckBox) dialog.getView().findViewById(R.id.md_promptCheckbox);

希望这能有所帮助。