Ωmega
Ωmega

Reputation: 43673

Access Android reference style color attribute programmatically

While in XML resources I can use a system reference style color like this (just an example):

android:textColor="?android:itemTextColor">

I would like to know how to get that color in java programmatically, when I need to set that color like this (unrelated another example):

button.setBackgroundColor(myColor);

How can I set myColor to be ?android:itemTextColor ?

Upvotes: 1

Views: 214

Answers (2)

lelloman
lelloman

Reputation: 14173

What you're seeing there is an attribute, it's a reference for a resource (not necessarily a color). An attributes is resolved by a Theme, this means that the same attributes can be resolved to different values according to the Theme by which are resolved.

If you are in an Acitivity you can (and probably should) use the Activity's theme

val typedValue = TypedValue()
val found = theme.resolveAttribute(android.R.attr.textColorHint,typedValue, true)

After that you should check the type of the value you've resolved

when(typedValue.type){
    TypedValue.TYPE_INT_COLOR_ARGB8 -> ...
    TypedValue.TYPE_INT_COLOR_ARGB4 -> ...
    ...
}

And then you could (eventually) use the value of the color which is stored in typedValue.data

Upvotes: 1

MidasLefko
MidasLefko

Reputation: 4549

Does something like this help?

TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.textColorHint, typedValue, true);
button.setBackgroundColor(typedValue.data);

Upvotes: 2

Related Questions