I am trying to retrieve text color in my Java code
TypedValue typedValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.textColor, typedValue, true);
int color = typedValue.data;
Taking reference of this and this questions.
But all the time I get 1637 but when I set it on textview Shader textView.getPaint().setShader(Gradient...) this color appears transparent.
How to solve this?
We are used to seeing colors represented in hex form, like #RRGGBB or #AARRGGBB. However, these hex codes are just numbers, and you're seeing the decimal representation of your color value.
If you use Color.valueOf() on the output, you should be able to get more information about the color in a manner you expect. For me, I wanted to look at the value of ?colorAccent, so I wrote this:
val typedValue = TypedValue()
theme.resolveAttribute(R.attr.colorAccent, typedValue, true)
val color = Color.valueOf(typedValue.data)
println(color)
And this is the output:
Color(0.84705883, 0.105882354, 0.3764706, 1.0, sRGB IEC61966-2.1)
That's telling me that my color is 84.7% red, 10.6% green, 37.6% blue with 100% opacity. I can also use a quick extension method to get the hex value:
private fun Color.toHexString(): String =
String.format("#%08X", toArgb())
This gives me the hex string #FFD81B60, which matches what I see in my colors file (though I specified it without an alpha channel).
If I run my code with your output (1637), I get this:
Color(0.0, 0.023529412, 0.39607844, 0.0, sRGB IEC61966-2.1)
(#00000665)
This is telling me that your color is 0% red, 2.4% green, and 39.6% blue... but also that it is 0% opaque. This matches the fact that you see this color as transparent when you use it in a shader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With