Programmatically set a view's color to ?android:attr color attributes

1.7k views Asked by At

I need to programmatically set a view's color to ?android:attr/textColorPrimary which is an attribute from the android's dark theme compatible attributes. Now it is possible to get colorButtonNormal with

R.attr.colorButtonNormal

But not ?android:attr/textColorPrimary and ?android:attr/colorBackground. Is there anyway to also get these attributes programmatically?

1

There are 1 answers

2
Gabriele Mariotti On BEST ANSWER

You can use android.R.attr.textColorPrimary.

Something like:

    val typedValue = TypedValue();
    theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
    val color = ContextCompat.getColor(this, typedValue.resourceId)

In Java:

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