Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks with custom font for set custom font

You should cache the TypeFace, otherwise you might risk memory leaks on older handsets. Caching will increase speed as well since it's not super fast to read from assets all the time.

public class FontCache {

    private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();

    public static Typeface get(String name, Context context) {
        Typeface tf = fontCache.get(name);
        if(tf == null) {
            try {
                tf = Typeface.createFromAsset(context.getAssets(), name);
            }
            catch (Exception e) {
                return null;
            }
            fontCache.put(name, tf);
        }
        return tf;
    }
}

I gave a full example on how to load custom fonts and style textviews as an answer to a similar question. You seem to be doing most of it right, but you should cache the font as recommended above.


I feel using the Font cache is not needed.Can we do this way?

A minor change to the above code, Correct me if i am wrong.

public class FontTextView extends TextView {
    private static final String TAG = "FontTextView";
    private static Typeface mTypeface;

    public FontTextView(Context context) {
        super(context);
    }

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

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getAssets(),   GlobalConstants.SECONDARY_TTF);
        }
        setTypeface(mTypeface);
    }

    }