Creating a TypeFace Helper Class

I have about 10-15 Activity or Fragment in my application. I have about 5 different types that I use (mostly Roboto options).

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 combination of 3.

Declaring this code in every class seems redundant. Is it possible to declare 5 fonts once, maybe when the application starts, and then I use the helper class to use them statically?

I'm not sure if I should do this - if at all possible - in a class extending the application, or just in a regular class that I can statically call? And where will it be initialized?

+4
source share
2 answers

I'm not sure I need to do this - if at all possible - in a class that extends the application, or just a regular class that I can call statically?

Anyway. There are several implementation examples that all "cache" the last few types of faces. If I remember correctly, on later Android platforms, caching also happens under the hood. In any case, the base implementation will 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 can also make it part of your own Application extension. It creates faces of the type lazily: it first tries to extract the type face from the local cache and only creates a new instance if it is not accessible from the cache. Just put Context and the type name of the person to load.

+8
source

If you are one of the few lucky ones using minApi 24, you donโ€™t need to do anything, since createFromAsset() has a Typeface cache, API 24 running. If not, check out @MH. Answer.

0
source

Source: https://habr.com/ru/post/1487948/


All Articles