Reputation: 57346
I'm fighting with a very strange behaviour in my Android app. I have a TextView
, where colours of background and text are set dynamically based on some conditions. To simplify, some condition is checked against an error and colours are set for the text view in this manner (note that the frame layout that the text view is added to has the background colour set to @android:color/black
):
TextView tv = new TextView(this);
((FrameLayout)this.findViewById(R.id.text_frame)).add(tv);
String val = getValue();
tv.setText(val);
if(isError(val)) {
tv.setBackGroundColor(R.color.bg_error);
tv.setTextColor(R.color.txt_error);
}
else {
tv.setBackGroundColor(R.color.bg_normal);
tv.setTextColor(R.color.txt_normal);
}
The colours are defined in XML like so:
<color name="bg_normal">#ffffff</color>
<color name="bg_error">#ff0000</color>
<color name="txt_normal">#0000ff</color>
<color name="txt_error">#008080</color>
I didn't expect anything weird of this code, as I used similar stuff before many times. However in this case, this code doesn't work. Regardless of what I try, the colours of text and background of the text view remain black.
Now, if I change my code to the following, everything works perfectly.
if(isError(val)) {
tv.setBackGroundColor(Color.rgb(255, 0, 0));
tv.setTextColor(Color.rgb(0, 128, 128));
}
else {
tv.setBackGroundColor(Color.rgb(255, 255, 255));
tv.setTextColor(Color.rgb(0, 0, 255);
}
While I can, of course, leave it like this (it works - why fix it?), I would much rather get the colours from XML as it would be so much easier to maintain and modify later.
Has anyone got any ideas as to what the problem might be and how to solve it?
P.S. I will preempt the suggestion that I create the text view in XML and set its colours there by saying that this is a simplified code. There are many text views like this created dynamically with their number depending on external parameter. At coding time, I don't know whether there will be 1 such text view or 100.
Upvotes: 0
Views: 124
Reputation:
setBackgroundColor()
takes a color encoded within an int. You supply a resource id though, which will generate wrong/different results.¹
Rather get the color encoded from the resources like this:
tv.setBackGroundColor(getResources().getColor(R.color.bg_normal));
¹ given that is weird design that you have to trip over, other resources setters also take an int, almost consistently for a res id. This is somewhat of a special case. :)
Upvotes: 3