2

Recently I changed a little bit of my app and for a reason I don't understand the "setTextColor" method seems that it no longer works.

In my XML, I have a listview and I programmatically add TextViews in this listView.

XML:

   <LinearLayout
        android:id="@+id/activity_game_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left|top"
        android:orientation="vertical"
        android:padding="7dp" >
    </LinearLayout>

Java:

textView = new TextView(getContext());
    textView.setText("some text");
    textView.setTextSize(20f);
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(Color.BLACK);
    textView.setTextAppearance(getContext(), android.R.style.TextAppearance_Medium);
    addView(textView);

But this text is white whatever I do. Why?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3659739
  • 434
  • 6
  • 19

4 Answers4

1

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

See this: TextView setTextColor() not working

Community
  • 1
  • 1
  • Thanks, but i forgot to say that i'm still in library 22. The answer that fix my problem is the one next to you. – user3659739 Sep 27 '16 at 19:18
1

I did try your code and I guess the troubling factor was setTextAppearance. In fact calling setTextColor() after this call fixed the issue. The below code is working perfectly for me:

        TextView textView = new TextView(this);
        textView.setText("some text");
        textView.setTextSize(20f);
        textView.setGravity(Gravity.CENTER);
        // textView.setTextColor(Color.RED);
        textView.setTextAppearance(this, android.R.style.TextAppearance_Medium);
        textView.setTextColor(Color.RED);
        // setContentView(textView);

I don't know the true reason for this issue.

Shaishav
  • 5,282
  • 2
  • 22
  • 41
0

You can use:

 ResourceCompact.getColor(getResources(), R.color.your_id, null);

The getResources().getColor() method is deprecated.

Shaishav
  • 5,282
  • 2
  • 22
  • 41
0

Use:

textView.setTextColor(Color.parseColor("#000000"));

instead of:

textView.setTextColor(Color.BLACK);
Shaishav
  • 5,282
  • 2
  • 22
  • 41
Vidit
  • 41
  • 4