Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros & Cons, keeping static references to Typeface for reuse across layouts?

I'm always looking for ways to improve my Android dev skills... Hence this question.

Do you foresee any possible cons or pros about storing Typeface's statically for different fonts as they are being used by the app?


Pros:

  • Load once use everywhere.

Cons:

  • More heap used?

My "TypeFace" cacher:

public static synchronized Typeface getFontType (String fontFile)
{
    if (!smTypefaces.contains(fontFile)) {
        try {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/"+fontFile);
            if (null != tf) {
                // todo use maybe a weak reference?
                smTypefaces.put(fontFile, tf);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    return smTypefaces.get(fontFile);
}
like image 464
Jona Avatar asked Nov 04 '22 02:11

Jona


1 Answers

I do exactly that, and I've never had a related memory issue. I created a class called FontProvider that lazy loads a static Map where the key is a string constant and the value is the instance of Typeface. I expose the map through a get(String key) method that returns null if the key isn't in the map.

like image 150
Rich Avatar answered Nov 09 '22 15:11

Rich