Reputation: 81
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
int color = ContextCompat.getColor(getContext(), mColorResourceId);
linearLayout.setBackgroundColor(color);
i have these line of code :
mColorResourceId
it's hold R.color.category_numbers
-> mColorResourceId = R.color.category_numbers
when i pass mColorResourceId
directly to setBackgroundColor(mColorResourceId);
it's doesn't change the color despite the method accept int
value .
my question why i need this extra step int color = ContextCompat.getColor(getContext(), mColorResourceId);
to change the color ??
Upvotes: 0
Views: 1193
Reputation: 234807
The setBackgroundColor()
method accepts an int
that is supposed to be a color value in aarrggbb
format. The resource ID R.color.category_numbers
is also an int
, but it is not a color value; instead it is the identifier of a color
resource. Calling ContextCompat.getColor(getContext(), mColorResourceId)
retrieves the actual color value corresponding to mColorResourceId
.
Part of the reason Android does this kind of indirection is to provide flexibility. The actual color returned may depend on the current theme or the device configuration and may actually change at run time (depending on how you declare your color resource).
Upvotes: 5