androidkotlinanko

How to set a custom font for android application?


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.


Solution

  • 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