Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView setTextColor() not working

I programmatically create a list (no a ListView, just adding them to the parent) of such elements:

    <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"      android:orientation="vertical" android:layout_weight="1">     <TextView android:id="@+id/filiale_name"     android:layout_width="fill_parent" android:layout_height="wrap_content"/>     <TextView android:id="@+id/lagerstand_text"     android:layout_width="fill_parent" android:layout_height="wrap_content"     android:textSize="10sp" android:textColor="@color/red"/> </LinearLayout> 

Also, I have defined some colors in values/colors.xml. As you see, the TextView with id "lagerstand_text" has set it's color to red by default. That works.

When creating the elements in Java, I do

lagerstandText.setText("bla"); 

and for some elements also I do

lagerstandText.setTextColor(R.color.red); 

and other colors. While the elements on which I don't call setTextColor() are red, all others are grey, no matter which color I chose (even if it's the same red again).

Why is that?

like image 684
didi_X8 Avatar asked May 30 '11 14:05

didi_X8


People also ask

How do I change text color in XML?

Android TextView – Text Color. TextView Text Color – To change the color of text in TextView, you can set the color in layout XML file using textColor attribute or change the color dynamically in Kotlin file using setTextColor() method.


1 Answers

The documentation is not very verbose about this, but you cannot use just the R.color integer when calling setTextColor. You need to call getResources().getColor(R.color.YOURCOLOR) to set a color properly.

Use the following to set color of your text programmatically:

textView.setTextColor(getResources().getColor(R.color.YOURCOLOR)); 

Starting with the support library 23 you have to use the following code, because getColor is deprecated:

textView.setTextColor(ContextCompat.getColor(context, R.color.YOURCOLOR)); 
like image 182
Sunil Kumar Sahoo Avatar answered Oct 07 '22 13:10

Sunil Kumar Sahoo