当我使用resolveAttribute()
找出?attr/colorControlNormal
的颜色值时,我得到了236
:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
// 236
但是,当我将XML布局与以下
TextView
元素一起使用时:<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代码:
View textView = findViewById(R.id.textView);
int color = ((TextView) textView).getCurrentTextColor();
// -1979711488
我得到的颜色值为
-1979711488
为什么这些结果会有所不同?我希望获得相同的颜色值,但事实并非如此。
第二种方法(我相信)返回正确的颜色值。为什么我的第一种方法是错误的?
我希望获得
?attr/colorControlNormal
的颜色值,而无需使用实际元素。我怎样才能做到这一点? 最佳答案
我相信除了: 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)