Skip to content Skip to sidebar Skip to footer

Change Checkbox Text Color When Checked

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

Solution 1:

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

/res/color/text_my_checked.xml

<selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:state_checked="true"android:color="#ffcc00"/><!-- checked --><itemandroid: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.

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

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

Solution 2:

You might do that programmatically, recalling your Checkbox and setting an onCheckedChangeListener.

CheckBoxcb= (CheckBox) findViewById(R.id.checkbox);
    cb.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() {
        @OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) { buttonView.setTextColor(...) }
            if (!isChecked) { buttonView.setTextColor(...); }
        }
    });

Solution 3:

I'm not sure why there isn't mentioned setting the text color through xml. If you create text_my_checked.xml like @Eugen mentioned. You are able to set it in xml like this

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

Post a Comment for "Change Checkbox Text Color When Checked"