android – Performance issue on custom font TextView-ThrowExceptions

Exception or error:

I have a custom TextView, with a personalized font attribute:

public class TextViewPlus extends TextView {
    private static final String TAG = "TextViewPlus";
    public TextViewPlus(Context context) {
    public TextViewPlus(Context context, AttributeSet attrs) {
        // This is called all the time I scroll my ListView
        // and it make it very slow. 
        super(context, attrs);
        setCustomFont(context, attrs);
    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
            tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
        } catch (Exception e) {
            Log.e(TAG, "Could not get typeface: "+e.getMessage());
            return false;
        return true;

I’m using it in my XML files with the attribute customFont=”ArialRounded.ttf”, and it is working quite well.

I’m using this TextViewPlus in a ListView, populated with an ArrayAdapter.

TextViewPlus dataText = (TextViewPlus) itemView.findViewById(;
dataText.setText("My data String");

My problem is that the performance, when I’m scrolling the ListView, are terrible! Very slow and full of lags. The TextViewPlus constructor n°2 it’s called all the time i scroll the list.

If I change TextViewPlus in a normal TextView, and use dataText.setTypeface(myFont), everything is smood and is working well.

How can I use my TextViewPlus without performance issue?

How to solve:

Why don’t you keep the created typface object in memory so that you don’t create every time the text view is getting created.

Following is a sample class that creates and cache the typeface object:

public class TypeFaceProvider {

    public static final String TYPEFACE_FOLDER = "fonts";
    public static final String TYPEFACE_EXTENSION = ".ttf";

    private static Hashtable<String, Typeface> sTypeFaces = new Hashtable<String, Typeface>(

    public static Typeface getTypeFace(Context context, String fileName) {
    Typeface tempTypeface = sTypeFaces.get(fileName);

    if (tempTypeface == null) {
        String fontPath = new StringBuilder(TYPEFACE_FOLDER).append('/').append(fileName).append(TYPEFACE_EXTENSION).toString();
        tempTypeface = Typeface.createFromAsset(context.getAssets(), fontPath);
        sTypeFaces.put(fileName, tempTypeface);

    return tempTypeface;

Leave a Reply

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