Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Google Fonts .xml programmatically to TextView

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!

like image 843
Matze G. Avatar asked Sep 17 '17 13:09

Matze G.


People also ask

How do I set text font view?

Right-click the font folder and go to New > Font resource file. The New Resource File window appears. Enter the file name, and then click OK. The new font resource XML opens in the editor.

Which API can be used to change the text font?

First, the default is not Arial. The default is Droid Sans. Second, to change to a different built-in font, use android:typeface in layout XML or setTypeface() in Java.

How do you underline text in XML?

Just use <u> and <\u> in XML, and it's enough.


1 Answers

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.

like image 199
Tharkius Avatar answered Oct 23 '22 12:10

Tharkius