How to get the value of a color property programmatically… here is a solution to the problem.
How to get the value of a color property programmatically
When I use resolveAttribute()
to find the color value of ?attr/colorControlNormal
, I get 236
:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
236
But when I use an XML layout with the following TextView
element:
<TextView
android:id="@+id/textView"
style="?android:attr/textAppearance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/colorControlNormal"
android:text="@null" />
… and the following Java code:
View textView = findViewById(R.id.textView);
int color = ((TextView) textView).getCurrentTextColor();
-1979711488
I get a color value of -1979711488
Why are these results different? I was expecting the same color value, but it wasn’t.
The second method (I believe) returns the correct color value. Why is my first method wrong?
I prefer to get the color value of ?attr/colorControlNormal
without using the actual element. What should I do?
Solution
I believe not this :
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
You should do this:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = ContextCompat.getColor(this, typedValue.resourceId)