didi_X8 didi_X8 - 1 year ago 282
Android Question

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"/>

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


and for some elements also I do


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?

Answer Source

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:


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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download