高效的字体加载
加载自定义字体可能会导致性能下降。我强烈建议使用这个小帮手将你已经使用的字体保存/加载到 Hashtable 中。
public class TypefaceUtils {
private static final Hashtable<String, Typeface> sTypeFaces = new Hashtable<>();
/**
* Get typeface by filename from assets main directory
*
* @param context
* @param fileName the name of the font file in the asset main directory
* @return
*/
public static Typeface getTypeFace(final Context context, final String fileName) {
Typeface tempTypeface = sTypeFaces.get(fileName);
if (tempTypeface == null) {
tempTypeface = Typeface.createFromAsset(context.getAssets(), fileName);
sTypeFaces.put(fileName, tempTypeface);
}
return tempTypeface;
}
}
用法:
Typeface typeface = TypefaceUtils.getTypeface(context, "RobotoSlab-Bold.ttf");
setTypeface(typeface);