views:

10004

answers:

4

Setting the background color programatically of an android TextView doesn't seem to work. I'm I missing something!

TextView et = new TextView(activity);
et.setText("350");
et.setBackgroundColor(R.color.white);

I also have this file (colors.xml) in my res/values folder

<resources>
        <color name="white">#ffffffff</color>
        <color name="black">#ff000000</color>
</resources>

[EDIT]: Also, setting the text color causes the TextView to disappear.

TextView c1 = new TextView(activity);
c1.setTextColor(R.color.solid_red);
c1.setText("My Text");
+14  A: 

Use et.setBackgroundResource(R.color.white);

bhatt4982
The android API is really something, why couldn't it throw an error?
Tawani
Because it is not an error. setBackgroundColor() takes a color in numeric form (e.g., 0xFFFF0000 for red). R.color.white is also a number.
CommonsWare
A: 

What will be the alternative for setting text color this way ?

Vikram
+11  A: 

Try this:

TextView c1 = new TextView(activity);
c1.setTextColor(getResources().getColor(R.color.solid_red));
c1.setText("My Text");

I agree that a color and a resource have the same type, but I also spend a few hours to find this solution.

Seb DA ROCHA
I don't fully understand it right now (looking over api doc's) but it does work, so thank you!
CodeJustin.com
A: 

Hey vikram, you can use android:textColor= " whatever text color u want to give" in xml file where your text view is declared.

Richa