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

4

所以我已经扩展了 TextView 来使用自定义字体(如这里所述),即:

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;
         }
     } 
}

我在活动的主要布局中添加一个片段,然后使用CustomTextView。一切正常,但是似乎存在一些内存问题,即每次旋转屏幕(导致活动经历其生命周期)时,字体资产都会加载到本机堆中,而不是替换之前的加载。例如:下面是使用Roboto-Light字体的adb shell dumpsys meminfo my.package.com的屏幕截图:

enter image description here

几次旋转后的相同屏幕截图如下:

enter image description here

很明显,在每次屏幕旋转时,资产分配本机堆都会增加(垃圾回收器也无法清除此类情况)。那么,我们肯定不能像上述方式那样使用自定义字体,如果不是这样,我们应该如何使用自定义字体呢?

1个回答

2

你应该在这里找到答案。

基本上你需要在创建字体后建立自己的缓存系统(因此你只需创建每个字体一次)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接