如何以编程方式将Google Fonts .xml设置为TextView

Mat*_* G. 5 xml fonts android google-fonts

从Android Studio 3.0开始,您可以简单地将google字体集成到您的项目中(请参阅android演练).

当您添加某些字体时,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>
Run Code Online (Sandbox Code Playgroud)

preloaded_fonts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="preloaded_fonts" translatable="false">
        <item>@font/amatic_sc</item>
    </array>
</resources>
Run Code Online (Sandbox Code Playgroud)

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

android:fontFamily="@font/amatic_sc"
Run Code Online (Sandbox Code Playgroud)

但在我的情况下,我需要在我的自定义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"));
Run Code Online (Sandbox Code Playgroud)

在我的情况下,我使用min SDK版本16,我希望我的代码片段足够.

谢谢您的帮助!

Tha*_*ius 14

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

Typeface typeface = ResourcesCompat.getFont(context,R.font.amatic_sc);
viewHolder.textView.setTypeface(typeface);
Run Code Online (Sandbox Code Playgroud)

更多信息在这里.


Mos*_*ter 0

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

Typeface font = Typeface.createFromAsset(mContext.getAssets(), fontPath);
v.setTypeface(font);
Run Code Online (Sandbox Code Playgroud)

注意:字体路径应该是

Roboto-Bold.ttf