【问题标题】:How to set Google Fonts .xml programmatically to TextView如何以编程方式将 Google 字体 .xml 设置为 TextView
【发布时间】:2018-02-26 02:59:04
【问题描述】:

从 Android Studio 3.0 开始,您可以简单地将谷歌字体集成到您的项目(See android walkthrough)。

当您添加一些字体时,Android Studio 会为您生成字体文件夹,其中包括字体的 XML 文件(在我的例子中是 amatic_sc.xml)。 Studio 还在 value 文件夹中创建了一个 preloaded_fonts.xml。

amatic_sc.xml:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto"
        app:fontProviderAuthority="com.google.android.gms.fonts"
        app:fontProviderPackage="com.google.android.gms"
        app:fontProviderQuery="Amatic SC"
        app:fontProviderCerts="@array/com_google_android_gms_fonts_certs">
</font-family>

preloaded_fonts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="preloaded_fonts" translatable="false">
        <item>@font/amatic_sc</item>
    </array>
</resources>

当我将以下行静态包含到我的 xml 文件中时,它可以正常工作:

android:fontFamily="@font/amatic_sc"

但在我的情况下,我需要在我的自定义 listAdapter 中以编程方式设置字体系列。我尝试了以下代码示例,但没有任何效果:

// Display text with default fontFamily
viewHolder.textView.setTypeface(Typeface.create("@font/amatic_sc", Typeface.NORMAL));

// both throws java.lang.RuntimeException: Font asset not found [../res/]font/amatic_sc.xml
viewHolder.textView.setTypeface(Typeface.createFromAsset(context.getAssets(), "font/amatic_sc.xml"));
viewHolder.textView.setTypeface(Typeface.createFromAsset(context.getAssets(), "../res/font/amatic_sc.xml"));

// both throws java.lang.RuntimeException: Font asset not found [../res/]font/amatic_sc.xml
viewHolder.textView.setTypeface(Typeface.createFromFile("font/amatic_sc.xml"));
viewHolder.textView.setTypeface(Typeface.createFromFile("../res/font/amatic_sc.xml"));

就我而言,我使用最小 SDK 版本 16,我希望我的代码 sn-p 就足够了。

感谢您的帮助!

【问题讨论】:

  • 嗨,Matze,您找到问题的解决方案了吗?我也面临同样的问题。
  • 目前我还没有解决方案:(

标签: android xml fonts google-fonts


【解决方案1】:

您可以使用支持库来兼容 8 之前的 android 版本,如下所示:

Typeface typeface = ResourcesCompat.getFont(context,R.font.amatic_sc);
viewHolder.textView.setTypeface(typeface);

更多信息here。

【讨论】:

    【解决方案2】:

    将字体文件保存在 assets 文件夹中,然后使用此片段

    Typeface font = Typeface.createFromAsset(mContext.getAssets(), fontPath);
    v.setTypeface(font);
    

    注意:字体路径应该是

    Roboto-Bold.ttf

    【讨论】:

      猜你喜欢
      • 2014-10-17
      • 2018-02-02
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-02-07
      • 2016-03-02
      • 1970-01-01
      • 2013-11-29
      相关资源
      最近更新 更多