How to use custom font as resource in Android

Issue #380

Downloadable fonts

https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts

Android 8.0 (API level 26) and Android Support Library 26 introduce support for APIs to request fonts from a provider application instead of bundling files into the APK or letting the APK download fonts. The feature is available on devices running Android API versions 14 and higher through the Support Library 26

Before

  • Select File -> New -> Folder -> Assets Folder to create src/main/assets/fonts
1
2
al myTypeface = Typeface.createFromAsset(assets, "fonts/myFont.ttf")
myTextView.typeface = myTypeface

In res

Create font directory

Right click res -> New -> Android Resource Directory, select font and name the folder font

Add custom fonts to res/font folder. Note that name must be lower case and underscore, like opensans_extrabolditalic.ttf

Right click res/font -> New -> Font resource file to create font family

opensans.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="utf-8"?>
<font-family
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<font
android:font="@font/opensans_regular"
android:fontStyle="normal"
android:fontWeight="400"
app:fontFamily="@font/opensans_regular"
app:fontStyle="normal"
app:fontWeight="400" />
<font
android:font="@font/opensans_semibold"
android:fontStyle="normal"
android:fontWeight="400"
app:fontFamily="@font/opensans_semibold"
app:fontStyle="normal"
app:fontWeight="400" />
<font
android:font="@font/opensans_bold"
android:fontStyle="normal"
android:fontWeight="400"
app:fontFamily="@font/opensans_bold"
app:fontStyle="normal"
app:fontWeight="400" />
</font-family>
```

Then use

```xml
<TextView
android:fontFamily="@font/opensans_bold"
android:textSize="26dp"
/>

Read more

Comments