如何在Android中更改开关的textcolor

Rob*_*n.v 18 android switch-statement android-4.0-ice-cream-sandwich

我正在创建一个使用Android 4.0的应用程序.我想知道是否可以更改开关中文本的文本颜色.

我已经尝试设置文本颜色,但它不起作用.

有任何想法吗?

提前致谢!

imb*_*ryk 63

您必须使用android:switchTextAppearance属性,例如:

android:switchTextAppearance="@style/SwitchTextAppearance"
Run Code Online (Sandbox Code Playgroud)

和风格:

<style name="SwitchTextAppearance" parent="@android:style/TextAppearance.Holo.Small">
    <item name="android:textColor">@color/my_switch_color</item>
</style>
Run Code Online (Sandbox Code Playgroud)

您也可以在代码中执行此操作,也使用以上样式:

mySwitch.setSwitchTextAppearance(getActivity(), R.style.SwitchTextAppearance);
Run Code Online (Sandbox Code Playgroud)

...并作为setTextColorSwitch-这种颜色会使用,如果你的SwitchTextAppearance风格不提供textColor

你可以在Switch源代码中检查它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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 我想知道他们为什么不能让`setTextColor`正常工作而不是所有这些膨胀. (6认同)