Android AL-Khatib Android AL-Khatib - 1 year ago 89
Android Question

explain the main reason to use getColor() method from ContextCompat class?

LinearLayout linearLayout = (LinearLayout) findViewById(;
int color = ContextCompat.getColor(getContext(), mColorResourceId);

i have these line of code :
it's hold
mColorResourceId = R.color.category_numbers

when i pass
directly to
it's doesn't change the color despite the method accept
value .

my question why i need this extra step
int color = ContextCompat.getColor(getContext(), mColorResourceId);
to change the color ??

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download