Custom fonts TextView in Android

Custom fonts TextView in Android

Nowadays, than ever before, everybody would like to use custom fonts in android TextViews.
It’s very easy to do it.

First step is to put the font in assets/fonts/Lato_Heavy.ttf

In this example we use Lato_Regular.ttf

Now, we are going to make a custom TextView, like this:

com.thedeveloperworldisyours
 
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
 
public class TextView_Lota_Heavy extends TextView {


    public TextView_Lota_Heavy(Context context) {
        super(context);
        applyCustomFont(context);
    }

    public TextView_Lota_Heavy(Context context, AttributeSet attrs) {
        super(context, attrs);
        applyCustomFont(context);
    }

    public TextView_Lota_Heavy(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        applyCustomFont(context);
    }

    private void applyCustomFont(Context context) {
        Typeface customFont = FontCache.getTypeface("fonts/Lato_Heavy.ttf", context);
        setTypeface(customFont);
    }
}

And FontCache

public class FontCache {
    private static HashMap<String, Typeface> fontCache = new HashMap<>();

    public static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);

        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), fontname);
            } catch (Exception e) {
                return null;
            }

            fontCache.put(fontname, typeface);
        }

        return typeface;
    }
}

when you want to load one of your custom fonts, you’d say something like:

Typefaces.get("Lato_Heavy");

basically this class ensures Android only loads each font once per instance of your app. the tradeoff, of course, is that each requested typeface object will remain in memory until your app is totally stopped by the OS (even though a given activity may not require each font).

Now we add our custom TextView in our layou.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background" >
  
    <com.thedeveloperworldisyours.TextView_Lota_Regular
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
  
</LinearLayout>

You can download this code: Download code

Leave a Reply

Your email address will not be published. Required fields are marked *