项目中遇到需求要动态改变字体,于是在网上找了一些字体样式进行设置,但是发现没过一会内存就占用特别高而且只增加不减,最后想到是每次加载字体都会调用
paint.setTypeface(Typeface.createFromAsset(context.getAssets(),"fonts/kaiti.ttf"))
此代码导致内存一直增加。后来写了一个字体单例工具类,可以在创建实例对象的时候加载一次字体即可,避免反复调用。
public class FontStyleUtils {
private volatile static FontStyleUtils instance;
private static Typeface localTypeface;
private FontStyleUtils (){}
public static FontStyleUtils getInstance(Context context) {
if (instance == null) {
synchronized (FontStyleUtils.class) {
if (instance == null) {
instance = new FontStyleUtils();
localTypeface = Typeface.createFromAsset(context.getAssets(),"fonts/kaiti.ttf");
}
}
}
return instance;
}
/**
* 楷体
* @return
*/
public static Typeface setFontType() {
return localTypeface;
}
}
这样直接调用即可
paint.setTypeface(FontStyleUtils.getInstance(control.getActivity()).setFontType());