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!
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.
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.
Just use <u> and <\u> in XML, and it's enough.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With