I'm trying to reset the TextColor of a TextView at runtime. I would like to get the default color for TextView as a @ColorInt
. I believe that the current Theme knows this.
Here's what I tried:
public @ColorInt int getDefaultThemeColor(int attribute) {
TypedArray themeArray = mContext.getTheme().obtainStyledAttributes(new int[] {attribute});
try {
int index = 0;
int defaultColourValue = 0;
return themeArray.getColor(index, defaultColourValue);
}
finally {
themeArray.recycle();
}
}
where attribute is:
android.R.attr.textColor
android.R.attr.textColorPrimary
android.R.attr.textColorSecondary
None of them worked to retrieve the right color. I've also tried to replace the first line of the method with:
TypedArray themeArray = mContext.getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {attribute});
I don't want the dirty solution of:
Any hint?
Define the following extension function (using kotlin):
@ColorInt
@SuppressLint("ResourceAsColor")
fun Context.getColorResCompat(@AttrRes id: Int): Int {
val resolvedAttr = TypedValue()
theme.resolveAttribute(id, resolvedAttr, true)
val colorRes = resolvedAttr.run { if (resourceId != 0) resourceId else data }
return ContextCompat.getColor(this, colorRes)
}
And then use it as follow:
val defaultText = context.getColorResCompat(android.R.attr.textColorPrimary)
The following code gives you a ColorStateList, which is not exactly what you asked for, but might be also applicable in the context where you need it:
TypedArray themeArray = theme.obtainStyledAttributes(new int[]{android.R.attr.textColorSecondary});
ColorStateList textColorSecondary = themeArray.getColorStateList(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With