Issue
I have already asked a question on this topic here but I could not understand why does it give a random color when it is reference? It should either give correct color which is not possible as it is reference or it should not even give any color. But why wrong color?
Thanks in advance 🙂
Solution
When you look inside the Android Sourcode you will find that there are two types of resource annotation @ColorRes and @ColorInt.
They are used as follow:
@ColorRes int myColorResource = R.color.myColor;
@ColorInt int myColorValue = getColor(myColorResource)
So basically, the color in Android is actually an integer value, which is endoded as:
int color = (A & 0xff) << 24 | (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
Where:
- A : Alpha
- R : Red component
- G : Green component
- B : Blue component
(You can read more about this at https://developer.android.com/reference/android/graphics/Color).
Now back to your question, the resources in android are actually represented by integer value, so your R.color.myColor would be holding integer value as 123456789 (This is random value generated at build, so for each build, you may get a different value for this. You can check this value by Logging it).
Now, Android consider this passed integer value as @ColorInt (resolved color value) instead of @ColorRes (resource, which needs to be resolved to achive the color value). As a result, the Android will try to extract A, R, G and B component from this value and render incorrect color.
References:
@ColorInt- https://developer.android.com/reference/androidx/annotation/ColorInt@ColorRes- https://developer.android.com/reference/androidx/annotation/ColorRes- Android Color object - https://developer.android.com/reference/android/graphics/Color
Answered By - Ashok
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.