【问题标题】:TextView text color changes on changing the background color更改背景颜色时 TextView 文本颜色更改
【发布时间】:2015-11-02 07:25:58
【问题描述】:

我在我的 android 应用程序中使用 TextView 作为 Button(平面 UI)。下面是代码

<TextView
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:background="@drawable/button_background"
            android:enabled="false"
            android:gravity="center"
            android:paddingBottom="16dp"
            android:paddingTop="16dp"
            android:text="Sign Up"
            android:textColor="@color/white"
            android:textSize="16sp"
            android:textStyle="bold" />

背景可绘制的'button_background'是

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#FCD5A5" android:state_enabled="false" />
<item android:drawable="#F7941E" />

所以当Button启用它应该有深橙色背景否则浅橙色背景。

背景颜色在两种状态(启用和禁用)下都可以正常工作但文本颜色也在发生变化。它在启用状态下保持白色,但在禁用状态下变为深灰色。我想在这两个州都保持白色。

【问题讨论】:

标签: android android-layout textview android-drawable xml-drawable


【解决方案1】:

我目前正在研究如何为您的选择器执行此操作。但就目前而言,您始终可以这样做并调用它一次进行初始化,然后在状态更改时调用它:

private void updateTextColor(TextView view, Context context) {
    if (!view.isEnabled()) {
        view.setTextColor(context.getResources().getColor(android.R.color.white));
    }
}

【讨论】:

    【解决方案2】:

    textcolorselector.xml

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:color="@color/general_blue" android:state_enabled="true"></item>
    <item android:color="@color/general_gray" android:state_enabled="false"></item>
    <item android:color="@color/general_blue"></item>
    

    将此行添加到 color.xml 文件中

     <drawable name="textviewcolor">@drawable/textcolorselector</drawable>
    

    最后将它应用到你的布局中

    <TextView
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:background="@drawable/button_background"
            android:enabled="false"
            android:gravity="center"
            android:paddingBottom="16dp"
            android:paddingTop="16dp"
            android:text="Sign Up"
            android:textColor="@color/textviewcolor" // <== i made change here!
            android:textSize="16sp"
            android:textStyle="bold" />
    

    【讨论】:

    • 这显示错误“textviewcolor”在 colors.xml 中不可用。你确定它是可编译的?
    • 对我来说很好,更新您的代码 color.xml、textcolorselector.xml 和布局
    猜你喜欢
    • 1970-01-01
    • 2018-12-25
    • 2014-06-12
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2013-09-27
    相关资源
    最近更新 更多