gpt4 book ai didi

android - 如何在 Android 中以编程方式设置谷歌字体

转载 作者:行者123 更新时间:2023-12-04 01:02:09 27 4
gpt4 key购买 nike

如何在 Android 中以编程方式设置谷歌字体

App is crash Caused by:android.content.res.Resources$NotFoundException: Font resource ID#0x7f090002 could not be retrieved.

 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

最佳答案

尽管以上两个答案都是正确的,但我将逐步详细介绍“可下载字体”,以便其他人理解。

Note: A device must have Google Play services version 11 or higher touse the Google Fonts provider.


  • 版面编辑 ,选择一个TextView,然后在下房产 , 选择 fontFamily > 更多字体 .
    enter image description here
  • 选择想要的字体并确保您选择创建可下载字体(在您的字体文件夹中创建 xml 文件)并单击 好的 .
    enter image description here

  • Android Studio automatically generates the relevant XML files that areneeded to render the font correctly in your app.


    现在,您可以像这样直接将其添加到 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

    关于android - 如何在 Android 中以编程方式设置谷歌字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67946776/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com