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

时间:2022-11-21 16:09:33

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

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

Any ideas ?

有任何想法吗 ?

1 个解决方案

#1


125  

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 ColorStateList for it and setting the textColor attribute to it instead of to a color.

我认为发生的事情是,因为你覆盖了默认的文本颜色,所以它不会继承其他的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文件示例。

#1


125  

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 ColorStateList for it and setting the textColor attribute to it instead of to a color.

我认为发生的事情是,因为你覆盖了默认的文本颜色,所以它不会继承其他的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文件示例。