选中复选框时改变文本颜色

13

当复选框被选中时,我希望更改文本的颜色。目前我的代码如下:

<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/>

当复选框被选中时,通常会改变其背景颜色。问题在于文本始终是相同的颜色。当复选框被选中时,如何改变文本颜色?

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

<?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>
3个回答

18
你也可以使用选择器,但是把它放在 /res/color 中,而不是 /res/drawable/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

编辑:

自从 appcompat-v7 24.0.0 版本以来,我们可以在 API 9 的平台上使用主题引用来设置颜色状态列表。这最初是在 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)以获取颜色状态列表。


4

您可以通过编程的方式做到这一点,调用您的Checkbox并设置onCheckedChangeListener

    CheckBox cb = (CheckBox) findViewById(R.id.checkbox);
    cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) { buttonView.setTextColor(...) }
            if (!isChecked) { buttonView.setTextColor(...); }
        }
    });

2

我不确定为什么没有提到通过XML设置文本颜色。如果您创建类似于@Eugen提到的text_my_checked.xml文件,您可以在XML中像这样进行设置:

<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:textColor="@drawable/text_my_checked"
    android:text="test/>

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