Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get font resource from TypedArray before API 26

Tags:

android

Android O introduced fonts in xml back to API 16 via the support library. However I am unable to find the support equivalent of TypedArray.getFont(), which required API level 26.

val array = context.obtainStyledAttributes(styleResId, R.styleable.TextAppearance)
val font = array.getFont(R.styleable.TextAppearance_android_fontFamily) // nope

Is there some kind of compat utility class I can use to retrieve a font from a style resource id?

like image 317
Tom Avatar asked Jul 26 '17 23:07

Tom


1 Answers

Found a workaround which is to find the resource ID of the font from the TypedArray, and then use ResourcesCompat to load the font.

val array = context.obtainStyledAttributes(styleResId, R.styleable.TextAppearance)
if (array.hasValue(R.styleable.TextAppearance_android_fontFamily)) {
    val fontId = array.getResourceId(R.styleable.TextAppearance_android_fontFamily, -1)
    val typeface = ResourcesCompat.getFont(context, fontId)
}
like image 117
Tom Avatar answered Oct 18 '22 13:10

Tom