Making a TypeFace Helper Class

后端 未结 2 399
既然无缘
既然无缘 2021-01-03 08:14

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

2条回答
  •  鱼传尺愫
    2021-01-03 08:31

    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 cache = new Hashtable();
    
        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.

提交回复
热议问题