Set Custom font for TextView and EditText in Android using fontFamily
Recent updates in Android APIs made it easier to add Custom fonts in TextViews and EditTexts. In this blog we will see how to add a Custom font in your TextView/EditText through XML just like adding TextSize or TextColor.
Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the
fontfile in the
res/font/folder to bundle fonts as resources. These fonts are compiled in your
Rfile and are automatically available in Android Studio. You can access the font resources with the help of a new resource type,
font. For example, to access a font resource, use
To use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26. For more information on using the support library, refer to the Using the support library section.
Steps to add Custom Fonts
First, we need to add a new Resource directory inside
res folder and click on
Android Resource Directory as shown in the screenshot below.
A New Resource Directory window appears. Change the Directory Name and Resource Type as
font (As shown below) and Click OK. It should be noted that the name of Resource Directory must be
Now if you check, you will find a
font directory inside
Copy – Paste all your Custom fonts inside this directory as shown below.
Now we are good to add these custom fonts into our TextViews and EditTexts directly through XML layout or Programatically.
Using XML :
android:fontFamily attribute inside your TextView / EditText Tags as shown below.
Here I am adding
avenirnext_bold from the
font directory. You may replace it with any fonts in your
font directory. You will see the Preview as shown below.
Adding custom font programatically is as easy XML as shown below. Here I am using Kotlin.
val typeface = resources.getFont(R.font.avenirnext_regular)
tvText.typeface = typeface
Run your code and check the TextView with custom font.
Hope you found this quick tutorial helpful. Please let me know your comments below.