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


当前回答

大多数答案都通过xml文件。如果你发现大多数Android版本都有一个活跃的答案,并且两种状态都只有一种颜色,检查和取消检查:下面是我的解决方案:

科特林:

val colorFilter = PorterDuffColorFilter(Color.CYAN, PorterDuff.Mode.SRC_ATOP)
CompoundButtonCompat.getButtonDrawable(checkBox)?.colorFilter = colorFilter

Java:

ColorFilter colorFilter = new PorterDuffColorFilter(Color.CYAN, PorterDuff.Mode.SRC_ATOP);
Drawable drawable = CompoundButtonCompat.getButtonDrawable(checkBox);
if (drawable != null) {
    drawable.setColorFilter(colorFilter);
}

其他回答

您可以通过将<CheckBox>嵌入到<LinearLayout>中来更改它的背景颜色。然后将<LinearLayout>的背景色更改为您想要的颜色。

我遇到了同样的问题,我用下面的技术得到了一个解决方案。将btn_check.xml从android-sdk/platforms/android-#(version)/data/res/drawable复制到项目的drawable文件夹,并将“on”和“off”图像状态更改为自定义图像。 然后你的xml将只需要android:button="@drawable/btn_check"

<CheckBox
    android:button="@drawable/btn_check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true" />

如果你想使用不同的默认Android图标,你可以使用:

android:button="@android:drawable/..."

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);

希望这能有所帮助。

使用buttonTint更改按钮和颜色选择器的颜色以上21+ api版本。

<android.support.v7.widget.AppCompatCheckBox
                android:id="@+id/check"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:buttonTint="@color/checkbox_filter_tint"
                tools:targetApi="21"/>

res /颜色/ checkbox_filter_tint。xml

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

你可以创建自己的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>