How to set Google Fonts .xml programmatically to TextView

8.3k views Asked by At

Since with Android Studio 3.0, you can simply integrate google fonts to your project (See android walkthrough).

When you add some font, Android Studio generates you the font folder including XML file for the font (in my case amatic_sc.xml). Also Studio create a preloaded_fonts.xml in value folder.

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>

When I'm include the following line static into my xml file, it works fine:

android:fontFamily="@font/amatic_sc"

But in my case I need to set the font family programmatically in my custom listAdapter. I tried following code exemples, but nothing works:

// 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"));

In my case, I use min SDK version 16 and I hope my code snippet is sufficient.

Thanks for the help!

2

There are 2 answers

0
Mostafa Anter On

save font file inside assets folder then use this snipt

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

notic: font path should some thing as

Roboto-Bold.ttf

0
Tharkius On

You can use the support library as to be compatible with android versions prior to 8, like this:

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

More info here.