【问题标题】:How to change textcolor of switch in Android如何在Android中更改开关的文本颜色
【发布时间】:2012-09-24 06:51:05
【问题描述】:

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

我试过设置文字颜色,但不起作用。

有什么想法吗?

提前致谢!

【问题讨论】:

  • 没有具体的代码,只是布局中的一个开关,通过ID找到。在代码中我设置了 switch.setTextColor(Color.WHITE);

标签: android switch-statement android-4.0-ice-cream-sandwich


【解决方案1】:

TextView.setTextColor() 采用一个表示颜色的 int(例如 0xFFF5DC49)而不是 xml 文件中的资源 ID。在活动中,您可以执行以下操作:

textView1.setTextColor(getResources().getColor(R.color.mycolor))

在活动之外,您需要一个上下文,例如。

textView1.setTextColor(context.getResources().getColor(R.color.mycolor))

更多信息请参考this

【讨论】:

  • 您好,首先感谢您的回复!这不是我正在寻找的答案,我让它适用于 textviews 和 editTexts。但我需要它来切换,我不确定如何..
  • 其实setTextColor不用于Switch,除非为android:switchTextAppearance提供的样式没有定义textColor
【解决方案2】:

我认为您必须查看您用于应用程序的主题。因为开关的颜色是主题的责任,afaik。所以我建议你看看如何更改主题的设置。或者您可以使用新颜色创建自定义主题。

【讨论】:

    【解决方案3】:

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

    android:switchTextAppearance="@style/SwitchTextAppearance"
    

    风格方面:

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

    你也可以在代码中做,同样使用上面的样式:

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

    ...对于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();
            }
        }
    

    【讨论】:

    • 我想知道他们为什么不能让setTextColor 正常工作而不是所有这些臃肿。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多