选中时更改复选框文本颜色 [英] Change checkbox text color when checked

查看:121
本文介绍了选中时更改复选框文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在选中CheckBox时更改文本的颜色.这就是我现在拥有的:

I would like to change color of the text when CheckBox is checked. This is what I have for now:

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:background="@drawable/states"
    android:gravity="center_horizontal|center_vertical"
    android:button="@null"
    android:text="test/>

选中复选框后,通常会更改复选框背景.问题是文本.它总是相同的颜色.选中复选框后,如何更改文本颜色?

Checkbox background is normally changed when checkbox is checked. The problem is text. It's always the same color. How can I also change text color when checkbox is checked?

这是我更改复选框背景状态的方式(由于简单起见,我删除了其他内容):

This is how I change states for checkbox background (I removed extras because of simplicity):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="false">
        <layer-list >
            <item>
                <shape android:shape="oval">
                </shape>
            </item>
        </layer-list>
    </item>

    <item android:state_checked="true" >
        <layer-list >
            <item>
                <shape android:shape="oval">
                </shape>
            </item>
        </layer-list >
    </item>
</selector>

推荐答案

您也可以使用选择器,但可以将/res/drawable 放在/res/color .

You can use selector as well but instead of /res/drawable put it in /res/color.

/res/color/text_my_checked.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#ffcc00"/> <!-- checked -->
    <item android:color="#ffffff"/> <!-- anything else -->
</selector>

通过调用 getResources().getColorStateList(R.color.text_my_checked),您将获得此颜色作为 ColorStateList .

You would get this color as ColorStateList by calling getResources().getColorStateList(R.color.text_my_checked).

从appcompat-v7 24.0.0开始,我们就可以在API 9之前的平台上的颜色状态列表中使用主题引用.这最初是在API 23中引入的.

Ever since appcompat-v7 24.0.0 we can use theme references in color state lists on platforms down to API 9. This was originally introduced in API 23.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="?colorControlActivated"/> <!-- checked -->
    <item android:state_checked="true" android:state_enabled="false" app:alpha="?android:disabledAlpha" android:color="?colorControlActivated"/> <!-- checked, disabled -->
    <item android:color="?android:textColorPrimary"/> <!-- anything else -->
</selector>

调用 AppCompatResources.getColorStateList(checkbox.getContext(),R.color.text_my_checked)以获得颜色状态列表.

Call AppCompatResources.getColorStateList(checkbox.getContext(), R.color.text_my_checked) to obtain the color state list.

这篇关于选中时更改复选框文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆