Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a TypeFace Helper Class

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?

like image 847
TheLettuceMaster Avatar asked Feb 17 '23 03:02

TheLettuceMaster


1 Answers

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.

like image 200
MH. Avatar answered Feb 28 '23 01:02

MH.