Using custom fonts in Android

Published on: July 23, 2013 Written by: Thokozani Mhlongo

In this post we are going to be working with setting custom fonts on a TextView. Setting a different typeface is fairly easy in android.

Applying the font

Here is a screenshot on where to put your font files:

Font file folder

 

Here is the our XML file with two TextView components:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:id="@+id/muro_typeface_view"
        android:text="@string/muro_font" />
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:id="@+id/myriad_typeface_view"
        android:text="@string/myriad_pro_text" />

</LinearLayout>

 

Now let's apply the fonts to our two views in our activity code:

package com.example.customtypeface;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Typeface;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TextView muroTypeFaceView = (TextView) findViewById(R.id.muro_typeface_view);
        TextView myriadTypeFaceView = (TextView) findViewById(R.id.myriad_typeface_view);
        
        Typeface muroFont = Typeface.createFromAsset(getAssets(), "MUROREGULAR.OTF");
        Typeface myriadFont = Typeface.createFromAsset(getAssets(), "MYRIADPRO-REGULAR.OTF");
        
        muroTypeFaceView.setTypeface(muroFont);
        myriadTypeFaceView.setTypeface(myriadFont);
    }

}

 

Here is the result below:

Font face in android

Comments