在API 26之前从TypedArray获取字体资源

Tom*_*Tom 8 android

Android O通过支持库将xml中的字体引入API 16.但是我无法找到相应的支持TypedArray.getFont(),这需要API级别26.

val array = context.obtainStyledAttributes(styleResId, R.styleable.TextAppearance)
val font = array.getFont(R.styleable.TextAppearance_android_fontFamily) // nope
Run Code Online (Sandbox Code Playgroud)

是否有某种compat实用程序类可用于从样式资源ID中检索字体?

Tom*_*Tom 21

找到一种解决方法,即从中查找字体的资源ID TypedArray,然后使用ResourcesCompat加载字体.

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)
}
Run Code Online (Sandbox Code Playgroud)

  • 字体字体= ResourcesCompat.getFont(context,fontId); (2认同)