设置未选中复选框的背景颜色 Android

18

它必须是这样的:

enter image description here

目前看起来是这样的:

enter image description here

圆角矩形并不是很重要。 但未选中状态必须为黑色。这是我的代码:

<CheckBox
    android:id="@+id/checkbox"
    android:buttonTint="@color/orange"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

这是我正在使用的主题:

  "Theme.AppCompat.Light.NoActionBar"

我也尝试过这个:

<style name="checkbox_style" parent="Bijenkorf">
    <item name="material_grey_600">@color/black</item>
</style>

因为默认未选中的颜色是#757575。我在主题中查找了这个颜色,它被称为“material_grey_600”。但是这无法编译。有什么想法吗?


您可以在这里跟随我的一个答案。您需要三个XML文件,一个用于自定义复选框,一个用于复选框被选中时,另一个用于复选框未被选中时,您在这里定义黑色的颜色。https://dev59.com/Q1gQ5IYBdhLWcg3wcTiH#42764334 - chirag90
@Jim Clermonts 请尝试这个 - Nisarg
请点击以下链接:https://dev59.com/jm025IYBdhLWcg3wsIIU - Ankita
3个回答

31

做法如下 -

在你的布局文件中 -

<android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:theme="@style/CheckboxStyle"/>

并且在您的style.xml文件中

<style name="CheckboxStyle" parent="AppTheme">
    <item name="colorAccent">@color/colorAccent</item>
</style>

或者您可以像这样更改选中和未选中的颜色-

<style name="CheckboxStyle" parent="AppTheme">
    <item name="colorAccent">@color/colorAccent</item>  // for checked 
    <item name="android:textColorSecondary">@color/colorSecondary</item>  // for unchecked
</style>

使用您需要的颜色更改 colorAccent和colorSecondary

希望这会对您有所帮助..


很高兴能帮助你.. :) - D_Alpha

20

我知道这个问题已经有答案了,但是可能有人会觉得这个有用。另一种实现方法是使用颜色状态列表,在xml文件中声明一个颜色状态列表来为复选框设置颜色。

checkbox_state_list.xml

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

现在将这个状态列表用作

<android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:buttonTint="@color/checkbox_state_list"/>

1
采纳的答案对我没有用,但这个完美地解决了我的问题。 - Big_Chair
被接受的答案对我来说并没有起作用,但是这个答案像魔法一样起了作用,+1。 - Wini

2
您需要像这样使用CheckBox样式:
在xml样式中:
 <style name="MyCheckBox" parent="Theme.AppCompat.Light">
        <item name="colorControlNormal">@color/white</item>
        <item name="colorControlActivated">@color/white</item>
 </style>

在 XML 布局中。
<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    style="@style/MyCheckBox"
    ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接