Using font in XML in API < 26
To complete Yuri's answer, Fonts are supported back to API 16.
To create font family (where different weights of fonts are specified), you should create my_font_family.xml
under /res/font/ as written in the doc:
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
<font app:fontStyle="normal" app:fontWeight="400" app:font="@font/myfont_regular"/>
<font app:fontStyle="normal" app:fontWeight="600" app:font="@font/myfont_semi_bold" />
<font app:fontStyle="italic" app:fontWeight="400" app:font="@font/myfont_italic" />
</font-family>
To use this in TextView
xml, you should use app:fontFamily="@font/my_font_family"
, be careful with app:
instead of android:
.
To choose specific fontWeight
, you can use android:textFontWeight="200"
but it only works on API>=28. To choose different font based on weight prior to API 28, you have two options. You can either use android:textStyle="bold"
to specify only "normal/italic/bold", but not exact weight. Or you can directly use specific weight of font like this: app:fontFamily="@font/myfont_semi_bold"
.
Please Note: If you are using custom textview, YourTextView
, in your app, it has to extend AppCompatTextView
and not merely android.widget.TextView
According to Google it is supported on Android 4.0+ (API 14+) as long as these conditions are met:
- You are using the support library version 26.0.0-beta1 or later
- You are using AppCompat
Sources:
Fonts in XML - Using the support library
Support Library revision history
I was hoping I could use this in app widgets on Android versions earlier than 8 (API 26), however it's not possible, as AppCompatTextView cannot be used in app widgets. None of the third party alternatives to Android O's 'Fonts in XML' such as the Caligraphy library work in app widgets either.
The only alternative for app widgets is using an ImageView instead of a TextView and using RemoteViews methods such as setImageViewUri(...) and setImageViewBitmap(...), both of which are problematic.
To support font family on API
lower than 26, we need to use
<font app:fontStyle="normal" app:fontWeight="400" app:font="@font/myfont-Regular"/>
instead of
<font android:fontStyle="normal" android:fontWeight="400" android:font="@font/myfont-Regular"/>