Set the Typeface and Style using font in Assets folder, in a TextView, in java

How to Set the Typeface and Style using font in Assets folder, in a TextView, in java

setTypeface was added in API Level 1
Related XML Attribute: android:fontFamily

setTypeface (Typeface tf)
Sets the typeface and style in which the text should be displayed. Note that not all Typeface families actually have bold and italic variants, so you may need to use setTypeface(Typeface, int) to get the appearance that you actually want.

1. Download a font to put in your Assets folder. For example, download the Droid_Robot Font. Unzip this fie and copy it to the assets folder in your project. The file should be named droidrobot.ttf. (Make sure it is spelled correctly.)

2. Find a TextView using ID for a Textview named myTextView.

3. In the MainActivity.java file, add the following the to imports section.

       import android.graphics.Typeface; 

4.Add the code below to the onCreate method. This will create a new typeface, named myTypeface,  from the specified font data.

Typeface myTypeface = Typeface.createFromAsset(getAssets(), "droidrobot.ttf");

5. Add the code below to the onCreate method. This sets the typeface and style in which the text should be displayed.

myTextView.setTypeface(myTypeface);

6. Compile and run!

Related Articles: