【问题标题】:How to get a value of color attribute programmatically如何以编程方式获取颜色属性的值
【发布时间】:2018-03-19 11:19:18
【问题描述】:

当我使用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 的颜色值。我该怎么做?

【问题讨论】:

  • 当你Log.dtypedValue.coerceToString()的值时,你在logcat上看到了什么?
  • @pskink res/color/secondary_text_material_light.xml
  • 那么简单的typedValue.toString()呢?
  • @pskink TypedValue{t=0x3/d=0xec "res/color/secondary_text_material_light.xml" a=1 r=0x10601e8}

标签: java android android-layout android-resources android-theme


【解决方案1】:

我相信不是这个:

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)

【讨论】:

  • 是否有类似的方法来获取?android:attr/textAppearance 样式的字体大小?或?android:attr/buttonBarNeutralButtonStyle 样式的字体颜色?请指教。谢谢。
  • 使用obtainStyledAttributes 传递android.R.attr.textAppearance。查看示例here
  • 样式包含许多属性,我假设。我如何将它与ta.getResourceId 一起使用?我应该使用什么索引来获取颜色以及获取字体大小的索引?我很迷惑。请说清楚。谢谢
  • 我假设这样:如果你已经指定,你想获取资源(a,b,c),那么为了获取a的值,你必须参考索引0,cs值将是index 2. 如果你知道 c 是一种颜色,那么你应该执行typedArray.getColor(2, 0)
  • 不,java.lang.UnsupportedOperationException: Can't convert value at index 0 to color: type=0x1
【解决方案2】:

我认为是正确的,请检查它

十六进制

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2014-01-30
    • 2021-06-27
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多