Get color value programmatically when it's a reference (theme)
This should do the job:
TypedValue typedValue = new TypedValue();Theme theme = context.getTheme();theme.resolveAttribute(R.attr.theme_color, typedValue, true);@ColorInt int color = typedValue.data;
Also make sure to apply the theme to your Activity before calling this code. Either use:
android:theme="@style/Theme.BlueTheme"
in your manifest or call (before you call setContentView(int)
):
setTheme(R.style.Theme_BlueTheme)
in onCreate()
.
I've tested it with your values and it worked perfectly.
To add to the accepted answer, if you're using kotlin.
@ColorIntfun Context.getColorFromAttr( @AttrRes attrColor: Int, typedValue: TypedValue = TypedValue(), resolveRefs: Boolean = true): Int { theme.resolveAttribute(attrColor, typedValue, resolveRefs) return typedValue.data}
and then in your activity you can do
textView.setTextColor(getColorFromAttr(R.attr.color))
We can use the utility class provided by Material Design library:
int color = MaterialColors.getColor(context, R.attr.theme_color, Color.BLACK)
NOTE: Color.BLACK
is the default color in case the attribute supplied to the u