Programmatically set text color to primary android textview
Extension version in kotlin
@ColorInt
fun Context.getColorResCompat(@AttrRes id: Int): Int {
val resolvedAttr = TypedValue()
this.theme.resolveAttribute(id, resolvedAttr, true)
val colorRes = resolvedAttr.run { if (resourceId != 0) resourceId else data }
return ContextCompat.getColor(this, colorRes)
}
usage:
textView.setTextColor(mActivity.getColorResCompat(android.R.attr.textColorPrimary))
You need to check if the attribute got resolved to a resource or a color value.
The default value of textColorPrimary is not a Color but a ColorStateList, which is a resource.
Kotlin solution
@ColorInt
fun Context.resolveColorAttr(@AttrRes colorAttr: Int): Int {
val resolvedAttr = resolveThemeAttr(colorAttr)
// resourceId is used if it's a ColorStateList, and data if it's a color reference or a hex color
val colorRes = if (resolvedAttr.resourceId != 0) resolvedAttr.resourceId else resolvedAttr.data
return ContextCompat.getColor(this, colorRes)
}
fun Context.resolveThemeAttr(@AttrRes attrRes: Int): TypedValue {
val typedValue = TypedValue()
theme.resolveAttribute(attrRes, typedValue, true)
return typedValue
}
Usage
@ColorInt val color = context.resolveColorAttr(android.R.attr.textColorPrimaryInverse)
Finally I used the following code to get the primary text color of the theme -
// Get the primary text color of the theme
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getActivity().getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
TypedArray arr =
getActivity().obtainStyledAttributes(typedValue.data, new int[]{
android.R.attr.textColorPrimary});
int primaryColor = arr.getColor(0, -1);