android 动态加载字体内存一直增加问题

项目中遇到需求要动态改变字体,于是在网上找了一些字体样式进行设置,但是发现没过一会内存就占用特别高而且只增加不减,最后想到是每次加载字体都会调用

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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值