80

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.

Any ideas ?

dsh
  • 12,037
  • 3
  • 33
  • 51
  • Here is the solution :D http://stackoverflow.com/questions/4692642/android-customized-button-changing-text-color – cesards Apr 23 '12 at 11:06
  • You have to manually set the text color to whatever you want. At least that's what I've had to do. – MattC Aug 27 '09 at 19:48

1 Answers1

172

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.

In a color file (eg 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.

Jeremy Logan
  • 47,151
  • 38
  • 123
  • 143
  • 1
    Thanks! Very convenient to have it in one place. Just a side note. Instead of the "color" folder (which is not standard for 2.1, for example) you can put it into "xml" folder, and use it as "@xml/example". Also works well from styles.xml ! – halxinate Mar 08 '13 at 01:15
  • 3
    Is there a way to programmatically get the color of disabled text ? – android developer Jun 04 '16 at 07:22