当我使用resolveAttribute()
找出?attr/colorControlNormal
的颜色值时,我得到了236
:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
// 236
但是当我使用带有以下TextView
元素的XML布局时:
<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
的颜色值,而无需使用实际元素。我怎么能这样做?
答案 0 :(得分:7)
我相信而不是:
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)
答案 1 :(得分:0)
我认为这是正确的,用它来检查
HEX
Integer intColor = -1979711488138;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
或
int color = getCurrentTextColor();
int a = Color.alpha(color);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
答案 2 :(得分:0)
这对我有用:
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = ContextCompat.getColor(this, typedValue.data)
typedValue.data 而不是 typedValue.resourceId