当我使用
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
的颜色值,而不需要使用实际元素。我怎样才能做到这一点?
我相信而不是这个:
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);
使用 Kotlin,您可以执行以下操作来获取颜色:
val color = TypedValue().let {
requireContext().theme.resolveAttribute(R.attr.colorControlNormal, it, true)
requireContext().getColor(it.resourceId)
}
在 Kotlin 中,根据 @azizbekian 的回答,要做到这一点,你可以这样做:
val typedValue = TypedValue()
theme.resolveAttribute(com.google.android.material.R.attr.colorControlNormal, typedValue, true)
val color = ContextCompat.getColor(this, typedValue.resourceId)