Implementing custom fonts in Android on application level.

So you are an android developer and you are tired of writing following lines wherever you want to implement custom fonts in textview like:

TextView tx = (TextView)findViewById(R.id.textview1);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/font-name.ttf");
tx.setTypeface(custom_font);

Well I have got a pretty good solution for you that works on application level.

So let’s not waste any more of our time and get started

  1. Create an android project using your prefered IDE.

After you have created an android project let’s import custom fonts in your project.

Go to your main directory and create assets folder if it is not already created.

In your assets directory create fonts folder and paste the custom fonts that you want to implement in your application. I am using Lato fonts which you can download for free from here.

Cool now you are set. Let’s start some coding then.

2. First we will create a TypeFactory class to access all the custom typeface instances.

TypeFactory.java

This class basically returns the required instance of the typeface.

3. Now let’s implement CustomApp class that extends Application class. Extending application class allows us to maintain a global application state. We are going to implement singleton pattern on this class. For more information on singleton pattern refer this tutorial.

CustomApp.java

Warning : Add android:name=”.CustomApp” in your manifest as running the application without adding it will return null pointer exception.

I usually create a separate interface Constants that holds all my application level constants. Adding constants in your interface automatically make them public static final so it’s a good practice to store your constants in a single file.

4. Now let’s create CustomTextView class which will extend current TextView class of android. For more on creating custom views in android refer this tutorial.

CustomTextView.java

4. It will throw error as we are yet to implement attrs.xml so let’s go and create that. Create an xml file in values folder in res directory and name it attrs.xml.

attrs.xml

Assign the values of fonts as we have assigned it to constant. For example we have assigned 1 for regular in both constants and in attrs.xml. This will help us assign custom fonts in xml itself rather than programmatically changing fonts every time.

5. Now everything is set. Let’s add our custom view to our activity’s xml file.

content_main.xml

Add a XML namespace of app in your parent layout having content as http://schemas.android.com/apk/res-auto.

You can see we can use our CustomTextView class just as we use TextView but now we can easily change the fonts that we want in xml itself.

Here’s how it will look :

You can checkout the full code on github here.

Post any questions in the comment.

Suggest anything that is missing or seems inappropriate.

Share the article if you like it.