How to set google font programmatically in Android

Viewed 1200

How to set google font programmatically in Android

App is crash Caused by: android.content.res.Resources$NotFoundException: Font resource ID #0x7f090002 could not be retrieved.

 val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant)
 appVersionName.typeface = typeface

enter image description here

<?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="Halant"
        app:fontProviderCerts="@array/com_google_android_gms_fonts_certs">
</font-family>

enter image description here

2 Answers

Though above two answers are correct, I will give you step-by-step details about "Downloadable Fonts" so that other will understand.

Note: A device must have Google Play services version 11 or higher to use the Google Fonts provider.

  1. In the Layout Editor, select a TextView, and then under Properties, select fontFamily > More Fonts. enter image description here

  2. Select the font want and make sure you choose create downloadable font (creates xml file in your font folder) and click OK. enter image description here

Android Studio automatically generates the relevant XML files that are needed to render the font correctly in your app.

Now, you can directly add it in TextView like this:

android:fontFamily="@font/halant_light"
     

Or use Downloadable Fonts programmatically like this:

val request = FontRequest(
        "com.google.android.gms.fonts",
        "com.google.android.gms",
        "Halant", //your font
        R.array.com_google_android_gms_fonts_certs
    )
val callback = object : FontsContract.FontRequestCallback() {

    override fun onTypefaceRetrieved(typeface: Typeface) {
        // Your code to set the font goes here
    }

    override fun onTypefaceRequestFailed(reason: Int) {
        // Your code to deal with the failure goes here
        
    }
}
FontsContractCompat.requestFont(mContext, request, callback, mHandler)

If you don't want the above programmatic way you can use the below code which I tested and working perfectly:

val typeface = ResourcesCompat.getFont(applicationContext, R.font.halant_light)
fontText.typeface = typeface
val typeface = Typeface.create("sans-serif-condensed", Typeface.BOLD)
textView.typeface = typeface
Related