如何在 Android 中以编程方式设置 Google 字体。

4

如何在Android中以编程方式设置Google字体。

应用程序崩溃,原因是: android.content.res.Resources$NotFoundException:无法检索字体资源ID #0x7f090002。

 val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant)
 appVersionName.typeface = typeface

enter image description here

<?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="Halant"
        app:fontProviderCerts="@array/com_google_android_gms_fonts_certs">
</font-family>

enter image description here


你可以展示这些 XML 的内容吗? - snachmsm
你的 ttf 文件在哪里? - Morrison Chang
我没有TTF文件,我只是在Android Studio中添加了Google字体。 - Bolt UIX
1
你看过这个吗:https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml - Morrison Chang
2个回答

2
虽然前两个答案是正确的,但我将为您详细介绍“可下载字体”的步骤,以便其他人能够理解。

注意:设备必须拥有Google Play服务版本11或更高版本才能使用Google字体提供程序。

  1. 布局编辑器中,选择一个TextView,然后在属性下选择fontFamily > More Fontsenter image description here

  2. 选择所需的字体,并确保选择创建可下载字体(在您的字体文件夹中创建xml文件),然后单击OKenter image description here

Android Studio会自动生成相关的XML文件,以正确地呈现字体在您的应用程序中。

现在,您可以直接像这样将其添加到TextView中:

android:fontFamily="@font/halant_light"
     

或者像这样以编程方式使用可下载字体:

val request = FontRequest(
        "com.google.android.gms.fonts",
        "com.google.android.gms",
        "Halant", //your font
        R.array.com_google_android_gms_fonts_certs
    )
val callback = object : FontsContract.FontRequestCallback() {

    override fun onTypefaceRetrieved(typeface: Typeface) {
        // Your code to set the font goes here
    }

    override fun onTypefaceRequestFailed(reason: Int) {
        // Your code to deal with the failure goes here
        
    }
}
FontsContractCompat.requestFont(mContext, request, callback, mHandler)

如果您不想使用上述的编程方式,您可以使用下面的代码,我已经测试过它,能够完美运行:
val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant_light)
fontText.typeface = typeface

0
val typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD)
textView.typeface = typeface

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接