Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

android - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...