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.

Leave a Comment