禁用时,Android 文本视图颜色不会改变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1342410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:57:42  来源:igfitidea点击:

Android text view color doesn't change when disabled

androidcolorstextview

提问by Jeremy Logan

When I call setEnabled(false)for a TextViewobject the text color doesn't change. I expected it will be changed to gray. If I remove the line of android:textColorin my XML file, it backs to normal.

当我调用setEnabled(false)一个TextView对象时,文本颜色不会改变。我预计它会变成灰色。如果我删除android:textColorXML 文件中的行,它会恢复正常。

Any ideas ?

有任何想法吗 ?

回答by Jeremy Logan

I think what's happening is that since you're overriding the default textcolor it isn't inheriting the other textcolor styles. Try creating a ColorStateListfor it and setting the textColor attribute to it instead of to a color.

我认为正在发生的事情是,由于您覆盖了默认的 textcolor,因此它不会继承其他 textcolor 样式。尝试为它创建一个ColorStateList并将 textColor 属性设置为它而不是颜色。

In a color file (eg res/color/example.xml):

在颜色文件(例如 res/color/example.xml)中:

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

then in your layout:

然后在您的布局中:

<TextView
    android:text="whatever text you want"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/example" />

Note, I haven't done this in a while and I'm typing a lot of this from memory, so it may need a little tweaking. The ColorStateList docs (linked above) have a more fleshed-out example for the color XML file.

请注意,我已经有一段时间没有这样做了,而且我从记忆中输入了很多内容,因此可能需要进行一些调整。ColorStateList 文档(上面链接)有一个更丰富的颜色 XML 文件示例。