【问题标题】:Get font resource from TypedArray before API 26在 API 26 之前从 TypedArray 获取字体资源
【发布时间】:2017-07-27 08:44:13
【问题描述】:

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

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

【问题讨论】:

    标签: android


    【解决方案1】:

    找到了一个解决方法,就是从TypedArray找到字体的资源ID,然后使用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)
    }
    

    【讨论】:

    • 字体字体 = ResourcesCompat.getFont(context, fontId);
    • 没关系。只是可以缩短到一条线。谢谢你的帖子!
    • 哦,不-解决方案的一半是首先从 TypedArray 获取 fontId
    • 我在实施此解决方案时看到以下警告:“资源 @styleable/TextAppearance_android_fontFamily 在 com.android.support.design 中被标记为私有。不应引用私有资源;它们可能不会出现在任何地方,即使它们在哪里,它们也可能会在没有通知的情况下消失。要解决此问题,请将资源复制到您自己的项目中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2020-05-17
    • 2014-03-08
    • 2017-08-09
    相关资源
    最近更新 更多