Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value of color attribute programmatically

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?

like image 301
Ωmega Avatar asked Mar 19 '18 11:03

Ωmega


People also ask

How do I set color programmatically?

To set the color to the TextView widget, call setTextColor() method on the TextView widget reference with specific color passed as argument. setTextColor() method takes int as argument. Use android. graphics.

How do I change the background color in programmatically?

xml which is under the values folder,then you should call the following: root. setBackgroundColor(getResources(). getColor(R.color.name));


1 Answers

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)

like image 184
azizbekian Avatar answered Oct 11 '22 13:10

azizbekian