Use custom fonts with androidx

Viewed 1137

I'm currently trying to add a custom font family to my Android project which is using Androidx instead of the old support library.

But I can't seem to find a way to support font families in older SDK versions (23+) with the AndroidX libraries and everything I find online is mentioning the old support library.

My current font family file looks like this:

<font-family
             xmlns:app="http://schemas.android.com/apk/res-auto">

    <font
        app:fontStyle="normal"
        app:fontWeight="500"
        app:font="@font/raleway_medium"/>

    <font
        app:fontStyle="normal"
        app:fontWeight="700"
        app:font="@font/raleway_bold" />

    <font
        app:fontStyle="normal"
        app:fontWeight="600"
        app:font="@font/raleway_semibold" />

</font-family>

Is there a way to make this work on older SDK versions with the androidx libraries?

2 Answers

You have to declare your fonts with the app and with the android attributes. So it will work for "all" sdk versions.

<font
    android:font="@font/myfont"
    android:fontStyle="normal"
    android:fontWeight="400"
    app:font="@font/myfont"
    app:fontStyle="normal"
    app:fontWeight="400" />

When you declared your font you can apply it in xml via:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="android:fontFamily">@font/customfont</item>
    <item name="fontFamily">@font/customfont</item>
...

or programmatically via:

val typeface = ResourcesCompat.getFont(context, R.font.customfont)
textView.typeface = typeface

In your XML file, you should replace TextView with androidx.appcompat.widget.AppCompatTextView.

Related