Android has supported setting custom fonts from a long time, but it has always missed out on one feature, setting fonts in xml. It has only allowed using fonts programmatically. Android team has finally resolved this pitfall in Support Library 26. Now you can use fonts in xml, just like any other resource.

 

Using fonts in XML

  • First step that you need to do is download some font files. You can get some good looking font files easily, just search on Google or use fonts provided by Google itself.
  • Now you need to create the resource folder for fonts in your project. Right click on res -> go to New -> click on Android Resource Directory.

  • Place the downloaded font files(.ttf) into the fonts folder. I have downloaded 3 fonts: Economica, Satisfy and Tangerine.

  • Now you can refer to your font files directly from your xml. Use the fontFamily property to set the font from the resource directory.

 

Adding fonts Programmatically

You can set the fonts programmatically as well.

We use ResourcesCompact here because we need to make sure that this code runs perfectly on previous versions of Android. If you try to use the getFont method on the resources by using getResources then Studio will give an error as that function can only be used on API 26 or above, so make sure you use ResourcesCompat.

Below is how the layout will look.

Now you can use fonts in your app very easily, but try not to use too much of them, using a mixture of too many font styles can ruin the overall app appearance and specially the UX. Here are the material guidelines when using typography in your app.

Android Developers Documentation

Getting Started with Kotlin

Leave a Reply

Your email address will not be published.

14 − four =