Skip to content

Instantly share code, notes, and snippets.

@le0nidas
Created January 21, 2022 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save le0nidas/feb7982a4c2e328b1fc343c0d7585030 to your computer and use it in GitHub Desktop.
Save le0nidas/feb7982a4c2e328b1fc343c0d7585030 to your computer and use it in GitHub Desktop.
class FontAwareTextAppearanceSpan(
private val context: Context,
private val appearance: Int
) : TextAppearanceSpan(context, appearance) {
private var font: Typeface? = null
override fun updateMeasureState(ds: TextPaint) {
super.updateMeasureState(ds)
val font = getFont() ?: Typeface.DEFAULT
val oldStyle = ds.typeface?.style ?: 0
ds.typeface = Typeface.create(font, oldStyle)
}
private fun getFont(): Typeface? {
if (font != null) {
return font
}
val cleanFamilyName = getFontFamilyName() ?: return null
val appPackageName = context.applicationContext.packageName
val id = context.resources.getIdentifier(cleanFamilyName, "font", appPackageName)
return getFont(context, id).also { font = it }
}
private fun getFontFamilyName(): String? {
val attrs = intArrayOf(R.attr.fontFamilyName)
val a = context.obtainStyledAttributes(appearance, attrs)
val fontFamilyName = a.getString(0)
a.recycle()
return fontFamilyName
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment