32

I have a clickable TextView that I want to give some colors to. But I don't know how. Here are the relevant code snippets from my two files that I'm working with:

TextView title = new TextView(this);
title.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
title.setTextColor(R.color.textcolor);
title.setText(titleLine);
title.setTypeface(null, Typeface.BOLD);
title.setClickable(true);
title.setId(idLine);
title.setFocusable(true);

title.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

                /* Irrelevant code */                   

    }
});

And this is my textcolor.xml file:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="#000000"/> <!-- pressed -->
    <item android:state_focused="true"
          android:color="#000000"/> <!-- focused -->
    <item android:color="#000000"/> <!-- default -->
</selector>

When I use the textcolor-file by typing title.setTextColor(R.color.textcolor);, the textcolor just becomes grey, regardless if I press it or so. Which is strange since I have written "#000000" in all color fields.
But if I remove the setTextColor code, gets the textView a light grey color, and when I press it, it becomes black. But that aren't the colors that I want.

So, can anyone help me with this problem?

Just to clarify: I want to be able to specify the colors for the text when it's normal, pressed and focused.

1
  • For people referring this page via search, do refer my answer if you are looking to use colors and not ColorStateList. My solution works without writing any code in Java :) Feb 11, 2013 at 19:54

9 Answers 9

69

If you want to set stateful color from code, you need to pass in ColorStateList as an argument to setTextColor passing an int to the method results in setting the color to all the states. It also looks like your xml is not totally correct. Example from ColorStateList docs looks like(should be located like this: res/color/selector_txt.xml):

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@color/testcolor1"/>
    <item android:state_pressed="true" android:state_enabled="false" android:color="@color/testcolor2" />
    <item android:state_enabled="false" android:color="@color/testcolor3" />
    <item android:color="@color/testcolor5"/>
 </selector>

UPD on how to set a ColorStateList to text color:

ColorStateList cl = null;
try {
   XmlResourceParser xpp = getResources().getXml(R.color.selector_txt);
   cl = ColorStateList.createFromXml(getResources(), xpp);
} catch (Exception e) {}

Note: The method createFromXml(Resources, XmlPullParser parser) was deprecated in API level 23. Use createFromXml(Resources, XmlPullParser parser, Theme)

With XML its as easy as:

android:textColor="@color/selector_txt"
3
  • 1
    I changed my XML file to what you suggested, and I did some searching on how I was supposed to send a ColorStateList in the setTextColor method. And I found this useful post: anddev.org/post27828.html#p27828 So now it's all working correctly. :) However, I need to tweak the states a bit in the xml document. Mar 21, 2011 at 7:35
  • @Daniel Jonsson I've added the code from the post to the answer, so it would be easier for someone else. Mar 21, 2011 at 8:02
  • 1
    to set it programatically use this: myTextView.setTextColor(getResources().getColorStateList(R.color.selector_txt));
    – phil
    Apr 29, 2015 at 13:08
50

Step 1: Set the text color in xml like this

android:textColor="@color/text_color"

Step2: Create res/color/text_color.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:state_pressed="true"
      android:color="#ffffffff"/> <!-- pressed -->
<item android:state_focused="true"
      android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/>  <!--default -->

</selector>
1
  • @AlwaysConfused, why? What is a device, OS version?
    – CoolMind
    Oct 9, 2017 at 16:34
17

Try this one.. It worked for me:

File name: res/color/bg_tab_text_color.xml

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

Try setting the color in xml layout as:

android:textColor="@color/bg_tab_text_color"
1
  • perfect save my time dude :) Dec 8, 2018 at 14:18
10

Look in R.java class (it's generated automatically). You have something like that:

 public static final class color {
        public static final int gray_transparent=0x7f050001;
}

So in your code in line:

title.setTextColor(R.color.textcolor);

you're not setting values from textcolor.xml but int from R.java (which contains textcolor.xml address). The valid way to set color is:

title.setTextColor(getResources().getColorStateList(R.color.textcolor));
5
  • Thanks a lot for your help! Now it actually reads the colors from the file. :) However, I'm still having a problem. It just reads the default color. The color won't change if I click on the text, which is strange.Do you know what causes this? Mar 20, 2011 at 23:14
  • 3
    It should be getResources().getColorStateList, not getResources().getColor.
    – Patrick
    Aug 9, 2011 at 16:49
  • @Patrick yeah, getResources().getColorStateList is really worked.
    – anticafe
    Dec 16, 2011 at 8:04
  • Note that this method has been deprecated as of API 23: developer.android.com/reference/android/content/res/…
    – Jake Lee
    May 2, 2016 at 16:17
  • ContextCompat.getColorStateList(this,R.color.textcolor) can be used to get rid of deprecation. May 31, 2016 at 5:20
5

Here is a very simple way programmatically:

private void setColorStateList(TextView view) {
        int[][] states = new int[][] {
                new int[] { android.R.attr.state_pressed}, // pressed
                new int[] { android.R.attr.state_focused}, // focused
                new int[] { android.R.attr.state_enabled}  // enabled
        };

        int[] colors = new int[] {
                getResources().getColor(R.color.blue),
                getResources().getColor(R.color.green),
                getResources().getColor(R.color.green) 
        };

        ColorStateList list = new ColorStateList(states, colors);
        view.setTextColor(list);
        view.setClickable(true);
        view.setFocusableInTouchMode(true);
    }
2
  • 1
    Excellent, That's the way
    – ucMedia
    May 10, 2018 at 13:10
  • the best answer for those who need a programmatical solution! Works like a charm!
    – porlicus
    Jan 10, 2020 at 5:38
3

It's very easy.Try this one.. It worked for me:

File name: res/color/bg_tab_text_color.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" android:drawable="@color/blue" />

Try setting the color in xml layout as:

android:textColor="@color/bg_tab_text_color"
1

In res/drawable/tab_textColor.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="#FFFFFF" />
    <item android:state_pressed="true" android:color="#FFFFFF" />
    <item android:color="#CCCCCC" />
</selector>



<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/icon"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="5dp"
    android:text="@string/tab_indicator_home"
    android:textColor="@drawable/tab_textcolor"
    android:textSize="10sp"
    android:visibility="visible"
    tools:ignore="SmallSp" />
0

In res/color/text_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/white"
          android:state_selected="true"/>
    <item android:color="#8020e0"/>
</selector>

In layout:

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Word"
    android:textColor="@color/text_selector"
    android:textSize="12sp"/>

In code:

textView.setSelected(false); // To deselect.
textView.setSelected(true);
0

For me just this way worked:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/colorSelected" />
    <item android:state_pressed="false" android:color="@color/colorDefault" />
</selector>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.