How to change textcolor of switch in Android

Robin.v picture Robin.v · Oct 3, 2012 · Viewed 20.3k times · Source

I'm creating an application which uses Android 4.0. I'm wondering if it is possible to change the text color of the text in a switch.

I've tried setting the text color, but it doesn't work.

Any ideas?

Thanks in advance!

Answer

imbryk picture imbryk · Mar 29, 2013

You must use android:switchTextAppearance attribute, eg:

android:switchTextAppearance="@style/SwitchTextAppearance"

and in styles:

<style name="SwitchTextAppearance" parent="@android:style/TextAppearance.Holo.Small">
    <item name="android:textColor">@color/my_switch_color</item>
</style>

you can also do it in code, also using above styles:

mySwitch.setSwitchTextAppearance(getActivity(), R.style.SwitchTextAppearance);

...and as for setTextColor and Switch - this color will be used if your SwitchTextAppearance style doesn't provide a textColor

you can check it in Switch source code in setSwitchTextAppearance:

    ColorStateList colors;
    int ts;

    colors = appearance.getColorStateList(com.android.internal.R.styleable.
            TextAppearance_textColor);
    if (colors != null) {
        mTextColors = colors;
    } else {
        // If no color set in TextAppearance, default to the view's textColor
        mTextColors = getTextColors();
    }

    ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.
            TextAppearance_textSize, 0);
    if (ts != 0) {
        if (ts != mTextPaint.getTextSize()) {
            mTextPaint.setTextSize(ts);
            requestLayout();
        }
    }