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


当前回答

你可以设置复选框的android主题来获得你想要的样式的颜色。

<style name="checkBoxStyle" parent="Base.Theme.AppCompat">
    <item name="colorAccent">CHECKEDHIGHLIGHTCOLOR</item>
    <item name="android:textColorSecondary">UNCHECKEDCOLOR</item>
</style>

然后在布局文件中:

<CheckBox
     android:theme="@style/checkBoxStyle"
     android:id="@+id/chooseItemCheckBox"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

不像使用android:buttonTint="@color/CHECK_COLOR"这个方法在Api 23下工作

其他回答

您应该尝试下面的代码。这对我很有用。

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/checked" 
          android:state_checked="true">
        <color android:color="@color/yello" />
    </item>
    <!-- checked -->
    <item android:drawable="@drawable/unchecked" 
          android:state_checked="false">
        <color android:color="@color/black"></color>
    </item>
    <!-- unchecked -->
    <item android:drawable="@drawable/checked" 
          android:state_focused="true">
        <color android:color="@color/yello"></color>
    </item>
    <!-- on focus -->
    <item android:drawable="@drawable/unchecked">
        <color android:color="@color/black"></color>
    </item>
    <!-- default -->
</selector>

和复选框

<CheckBox
    Button="@style/currentcy_check_box_style"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="20dp"
    android:text="@string/step_one_currency_aud" />

我的目标是使用自定义复选框按钮并删除强调色按钮色调。我尝试了公认的答案,但现在却起作用了,这对我来说很管用:

在styles.xml文件中

<style name="Theme.Checkbox" parent="Widget.AppCompat.CompoundButton.CheckBox">
    <item name="android:button">@drawable/theme_checkbox_button</item>
    <item name="android:drawableLeft">@android:color/transparent</item>
    <item name="android:drawablePadding">10dp</item>
    <item name="android:buttonTint">@android:color/transparent</item>
    <item name="android:buttonTintMode">screen</item>
</style>

现在对于这个问题,唯一需要的属性是android:buttonTint和android:buttonTintMode

下面是一些额外的内容:

我需要使用一个自定义drawable,因此android:button设置了一个选择器drawable 我需要一些空格之间的盒子和文本,因此我遵循这个SO答案,并设置android: drawablleft和android:drawablePadding

我遇到了同样的问题,我用下面的技术得到了一个解决方案。将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/..."

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

程序版本:

int [][] states = {{android.R.attr.state_checked}, {}};
int [] colors = {color_for_state_checked, color_for_state_normal}
CompoundButtonCompat.setButtonTintList(checkbox, new ColorStateList(states, colors));