How to add custom fonts in Android

22.02.2016

In this tutorial, I have covered how to add custom fonts in Android.During Android application development, sometimes you want custom fonts for your TextViews, Buttons, etc. This tutorial will help you in defining custom fonts for different views.

Before starting, you need to download a font of your choice which we will be using for our project. You should get a font package which has extension ".ttf".

To add Custom fonts in Android, follow the steps>

1).To be able to used in application, it needs to be placed in assets/fonts folder (i.e. in "fonts" folder inside "assets"). If "fonts" folder does not exist you can create it yourself.

2).Create a TextView in xml:

3).Now this font can be accessed with the help of class TypeFace.

TypeFace class has a static method called createFromAsset which we will use to apply custom font. Parameters of createFromAsset are AssetManager and path of our required font. Default AssetManager can be accessed by getAssets() method. We will provide the absolute path of font package kept in assets/fonts.

Get the reference of TextView:

TextView textView = (TextView) getView().findViewById(R.id.textview1);

If you are using non-fragment structure, then:

TextView textView = (TextView) findViewById(R.id.textview1);

 

Then call static method createFromAsset() of class TypeFace to get fonts from asset:

Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(),"fonts/");

 

In our case:

Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Computerfont.ttf");

Make sure that you write name of font as it is because messing with its case might result in error.

You are almost done, just set this TypeFace object to your textview.

textView.setTypeface(typeface);

 

4).My onActivityCreated() looks like this:

 

@Override

public void onActivityCreated(Bundle savedInstanceState) {

super.onActivityCreated(savedInstanceState);
TextView textView = (TextView) getView().findViewById(R.id.textview1);

Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Computerfont.ttf");
textView.setTypeface(typeface);

}
loading