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:
<TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" />
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/<name of font>");
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); }
You will see your textview in the font provided.
Nowadays, Eclipse recommends the use of fragments as to support phone/tablet compatibility and that’s how we have done it in this example.
You can download source code here.
[download url1=”http://cdn.hayageek.com.s3.amazonaws.com/downloads/android/FontsExample.zip” title1=”Download Source of Custom Fonts in Android”]