How to get a value of color attribute programmatically

痞子三分冷 提交于 2020-03-18 05:20:29

问题


When I use resolveAttribute() to find out a color value of ?attr/colorControlNormal, I got 236:

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
int color = typedValue.data;
// 236 

But when I use an XML layout with the following TextView element:

<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" />

...and the following Java code:

View textView = findViewById(R.id.textView);
int color = ((TextView) textView).getCurrentTextColor();
// -1979711488

I got a color value of -1979711488


Why those results vary? I expected to get same color values, but they are not.

The second approach (I believe) returns a correct color value. Why is my first approach wrong?

I would prefer to obtain the color value of ?attr/colorControlNormal without a need of using actual element. How can I do that?


回答1:


I believe instead of this:


    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
    int color = typedValue.data;

You should do this:


    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorControlNormal, typedValue, true);
    int color = ContextCompat.getColor(this, typedValue.resourceId)




回答2:


It's correct I think, check with it

HEX

Integer intColor = -1979711488138;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);

or

int color = getCurrentTextColor();
int a = Color.alpha(color);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);


来源:https://stackoverflow.com/questions/49361702/how-to-get-a-value-of-color-attribute-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!