How to set a custom font for android application?

Viewed 11529

I can't seem to be able to change the standard android font to another in my application. I'm writing my app in Kotlin and I'm using Anko to lay it out. I've tried:

typeface = Typeface.create()
typeface = Typface.createFromAsset(assets, "font/font_name")
setTypeface(Typeface.createFromAsset(assets, "font/font_name"))

Thanks for the help.

5 Answers

I had the same problem on Android Studio 3.1 Canary with Kotlin

Here is the solution: for font/lobster_regular.ttf file

var typeFace: Typeface? = ResourcesCompat.getFont(this.applicationContext, R.font.lobster_regular)

Example:

enter image description here

private var _customFontTextView: TextView? = null
private var _typeFace:           Typeface? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    this.setContentView(R.layout.activity_main)

    this._initializeResources()
    this._initializeGUI()
}

private fun _initializeResources() {
    this._customFontTextView = this.findViewById(R.id.custom_font_text_view)
    this._typeFace           = ResourcesCompat.getFont(this.applicationContext, R.font.lobster_regular)
}

private fun _initializeGUI() {
    this._customFontTextView!!.setTypeface(this._typeFace, Typeface.NORMAL)
}

Also you can do more with downloadable fonts, here is the article from Google: https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts.html

this is a great and short way for do it :
1- create a folder named font in the res folder. 2- then put your font file in the font folder that you created. (we suppose your font file name is sample_font.ttf)
3- so now create a xml file in the font folder named sample.xml and put the following code in it

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:font="@font/sample_font"
        android:fontStyle="normal"
        android:fontWeight="500" />
</font-family>

4- now go to and open the res/values/styles.xml and then add following line code to the main style (common name is AppTheme)

<item name="fontFamily">@font/sample</item>  //put name of xml file in the font folder

now run the your app and you'll see your application font changed.

You can try this one, from my working code ( In Kotlin )

if you are in some other Class file, then use this one

var typeFaceBold: Typeface? =
    this.getApplicationContext()?.let { ResourcesCompat.getFont(it, R.font.sans_serif_bold) }
    tvAnonymousText.typeface = typeFaceBold

If you are using it in Activity, then you can write like this

var typeFaceBold: Typeface? = ResourcesCompat.getFont(this.applicationContext, R.font.sans_serif_bold) }
tvAnonymousText.typeface = typeFaceBold
Related