Making a TypeFace Helper Class

后端 未结 2 406
既然无缘
既然无缘 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<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.

    0 讨论(0)
  • 2021-01-03 08:46

    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.

    0 讨论(0)
提交回复
热议问题