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

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

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

这样的

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

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

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

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


不信你可以这样看看

adb shell dumpsys meminfo +包名

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

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

几次界面切换,我的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" />


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

相关文章: