在Android中正确使用自定义字体

所以我扩展了TextView以使用自定义字体(如
here所述),即

public class CustomTextView extends TextView {
    public static final int CUSTOM_TEXT_NORMAL = 1;
    public static final int CUSTOM_TEXT_BOLD = 2;

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initCustomTextView(context, attrs);
    }

    private void initCustomTextView(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0);
        int typeface = array.getInt(R.styleable.CustomTextView_typeface, CUSTOM_TEXT_NORMAL);
        array.recycle();
        setCustomTypeface(typeface);
    }

    public setCustomTypeface(int typeface) {
         switch(typeface) {
             case CUSTOM_TEXT_NORMAL:
                 Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "customTextNormal.ttf");
                 setTypeface(tf);
                 break;
             case CUSTOM_TEXT_BOLD: 
                 Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "customTextBold.ttf");
                 setTypeface(tf); 
                 break;
         }
     } 
}

然后我在添加到activity的主要布局的片段中使用CustomTextView.一切正常,但似乎存在一些内存问题,即每次旋转屏幕(导致活动经历其生命周期)时,除了先前的加载外,字体资产也会加载到本机堆中.例如;下面是初始加载后没有屏幕旋转的adb shell dumpsys meminfo my.package.com的屏幕转储(使用Roboto-Light字体):

和一些旋转后相同的屏幕转储

显而易见的是每次屏幕旋转时资产分配和原生堆的增加(GC也不会清除它).当然,我们不应该以上述方式使用自定义字体,如果没有,我们应该如何使用自定义字体?

最佳答案 你应该找到你的答案
here.

基本上,您需要构建自己的系统来在创建它们之后缓存这些字体(因此您只需创建一次每个字体).

点赞