android TextView: setting the background color dynamically doesn't work

Viewed 279078

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");
16 Answers

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.

For setting colors from resource follow this:

textView.setBackgroundColor(getResources().getColor(R.color.ButtonColorRed));

Here ButtonColorRed is color name in color resource

If you try the above solutions and it still doesn't work, have a look at your TextView xml and make sure that you remove android:background (cuz it may overlap your et.setBackGroundColor(R.color.yourcolor)

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

Related