如何以编程方式获取颜色属性的值
How to get a value of color attribute programmatically
当我用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
为什么这些结果不同?我希望获得相同的颜色值,但事实并非如此。
第二种方法(我相信)returns 正确的颜色值。为什么我的第一种方法是错误的?
我更愿意在不需要使用实际元素的情况下获得 ?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)
我认为是正确的,检查一下
十六进制
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);
当我用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
为什么这些结果不同?我希望获得相同的颜色值,但事实并非如此。
第二种方法(我相信)returns 正确的颜色值。为什么我的第一种方法是错误的?
我更愿意在不需要使用实际元素的情况下获得 ?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)
我认为是正确的,检查一下
十六进制
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);