关于android text view 加载第三方字库导致内存泄漏问题

最近项目里接到了一个需求,app里面不同的文本使用不同的字体样式

通常来说,你在百度上一搜,结果是这样的


这样的


以上方法都能实现,但是第一种方法每次加载一个自定义文本框,就会加载一次字库,

第二种方法只适用于少量 activity ,如果是大量的fragment 那就不太科学了,

一般字库大小也好几M,加载多几次就导致内存暴增了


不信你可以这样看看

adb shell dumpsys meminfo +包名


注意红色框框,每次加载都会添加一个,(上图为优化后结果)

几次界面切换,我的app运行内存竟然达到200m。。。


网上查了很多调用第三方字体的用例,都是用这种方法,难道他们都没注意到内存?


我的解决方法,就是把字库加载为全局变量



public class App extends Application {

    public static Typeface typeface;
    public static Typeface typeface2;

    @Override
    public void onCreate() {
        super.onCreate();

        typeface = Typeface.createFromAsset(getAssets(), "fonts/Fzy3jw.ttf");
        typeface2 = Typeface.createFromAsset(getAssets(), "fonts/fzcy.ttf");
        
    }

}
调用的时候 
public class CustomFontContent extends TextView {


    public CustomFontContent(Context context) {
        super(context);
    }

    public CustomFontContent(Context context, AttributeSet attrs) {

        super(context, attrs);

    }

    public CustomFontContent(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);

    }

    public void setTypeface(Typeface tf, int style) {

        super.setTypeface(App.typeface);

    }

}
<cn.dlj.XXX.utils.CustomFontTextView
    android:id="@+id/notice_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:gravity="bottom"

    android:maxWidth="700dp"
    android:text="-"
    android:textColor="@color/main_text_color"
    android:textSize="@dimen/activity_main_notice_title" />

 
完事,全局变量只加载一次,之后你怎么使用都不会增加内存

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值