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).
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.
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.