Change checkbox text color when checked

空扰寡人 提交于 2019-12-05 05:40:55

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>

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

EDIT:

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>

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

You might do that programmatically, recalling your Checkbox and setting an 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(...); }
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!