Android AL-Khatib
Android AL-Khatib

Reputation: 81

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

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

Answers (1)

Ted Hopp
Ted Hopp

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

Related Questions