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?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With