如何以编程方式获取颜色属性的值 [英] How to get a value of color attribute programmatically
问题描述
当我使用resolveAttribute()
找出?attr/colorControlNormal
的颜色值时,我得到了236
:
When I use resolveAttribute()
to find out a color value of ?attr/colorControlNormal
, I got 236
:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
// 236
但是当我将XML布局与以下TextView
元素一起使用时:
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" />
...以及以下Java代码:
...and the following Java code:
View textView = findViewById(R.id.textView);
int color = ((TextView) textView).getCurrentTextColor();
// -1979711488
我的颜色值为-1979711488
为什么这些结果有所不同?我希望获得相同的颜色值,但事实并非如此.
Why those results vary? I expected to get same color values, but they are not.
第二种方法(我相信)返回正确的颜色值.为什么我的第一种方法是错误的?
The second approach (I believe) returns a correct color value. Why is my first approach wrong?
我希望获得?attr/colorControlNormal
的颜色值,而无需使用实际元素.我该怎么办?
I would prefer to obtain the color value of ?attr/colorControlNormal
without a need of using actual element. How can I do that?
推荐答案
我相信可以代替:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
您应该这样做:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = ContextCompat.getColor(this, typedValue.resourceId)
这篇关于如何以编程方式获取颜色属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!