Making a TypeFace Helper Class

2019-02-10 14:17发布

I have about 10-15 Activity's or Fragment's in my app. I have about 5 different TypeFaces I am using (mostly Roboto variants).

In almost every Class I have to do this:

roboto_light = Typeface.createFromAsset(getActivity().getAssets(),
        "fonts/roboto_light.ttf");
roboto_thin = Typeface.createFromAsset(getActivity().getAssets(),
        "fonts/roboto_thin.ttf");
roboto_regular = Typeface.createFromAsset(getActivity().getAssets(),
        "fonts/roboto_regular.ttf"); 

Not all classes use all five. Some use 1, some use 4, some use 3, while others may use a different combo of 3.

Declaring this code in every class seems redundant. Can the 5 fonts all be declared once, maybe when app starts and then I use a Helper Class to statically use them?

I am not sure if I have to do this -- if possible at all -- in a class that extends Application, or just a regular Class that I can statically call? And where would this be initialized?

2条回答
贪生不怕死
2楼-- · 2019-02-10 14:37

I am not sure if I have to do this -- if possible at all -- in a class that extends Application, or just a regular Class that I can statically call?

Either way will do. There are a couple of sample implementations out there, which all 'cache' the last few type faces created. If I recall correctly, in more recent Android platforms caching also happens under the hood. Anyways, a basic implementation would look like this:

public class Typefaces{

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

    public static Typeface get(Context c, String name){
        synchronized(cache){
            if(!cache.containsKey(name)){
                Typeface t = Typeface.createFromAsset(c.getAssets(), String.format("fonts/%s.ttf", name));
                cache.put(name, t);
            }
            return cache.get(name);
        }
    }    
}

Source: https://code.google.com/p/android/issues/detail?id=9904#c3

This is using a helper class, but you could also make it part your own Application extension. It creates type faces lazily: it attempts to retrieve the type face from the local cache first, and only instantiates a new one if not available from cache. Simply supply a Context and the name of the type face to load.

查看更多
我想做一个坏孩纸
3楼-- · 2019-02-10 14:48

If you are one of the few lucky ones using minApi 24 you don't have to do anything at all as createFromAsset() has a Typeface cache implemented starting API 24. If not, refer to @MH.'s answer.

查看更多
登录 后发表回答