Getting default TextView textColor in Android for current Theme

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)

Tags:

Android

Themes