Setting custom font through XML with DataBinding

Today we will learn about setting custom font through XML with DataBinding. We already know how to set custom font through java code.

It will set font type for given TextView or other View. But what if we have more number of TextViews/EditTexts throughout the application and that also with multiple custom fonts? We need to declare those number of objects for TextView/EditText as well as for TypeFace declaration. Don’t you think it will increase number of codes? Yes, so other option will come in your mind is to create Custom TextView/EditText. Not a bad idea but we have 15-20 custom fonts throughout the app so creating those number of Custom class would realy be a bad idea. So what is the simplest and easy solution? Answer is DataBinding.

Yes with the help of DataBinding you will be able to set custom font with just one line and that also without creating any object of TextView/EditText. sounds interesting? Let’s follow step by step instruction to implement that :

Step 1 : Implement DataBinding in your android studio project, refer previous tutorial to setup DataBinding “Working with DataBinding Android“.

Step 2 : Create custom class for storing and accessing custom fonts.

Step 3 : Define custom font in Applicaiton class.

Note : All the fonts defined in Application class must be available under asstes/fonts folder.

Custom font

Step 4 : Write Binding class to use fonts through out the application.

Step 5 : Access fonts from xml.

Step 6 : Final step is to bind your activity with a view.

Custom font

Above code will work perfectly but it will create object of TypeFace each time we set font. What we will do next is to store that TypeFace in cache, so next time it will take TapeFace from cache instead of creating new object. There will be minor change you need to do in your CustomFontFamily.java

Now whenever there is new TypeFace object created it will be stored in HashMap so next time it will be taken from map object. You will love this FontBinding Library by Lisa Wray.

Download source code

Working with Data Binding Android
Image Loading With DataBinding in Android