【问题标题】:Using Custom Fonts Properly in Android在 Android 中正确使用自定义字体
【发布时间】:2014-05-03 18:00:10
【问题描述】:

所以我扩展了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;
         }
     } 
}

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

旋转几次后,屏幕转储相同

清楚的是每次屏幕旋转时发生的资产分配本机堆的增加(GC 也不会清除这一点)。当然,我们不应该以上述方式使用自定义字体,如果不是,我们应该如何使用自定义字体?

【问题讨论】:

    标签: android memory memory-leaks fonts


    【解决方案1】:

    您应该会找到答案here

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 2020-12-05
      • 2013-05-13
      • 1970-01-01
      相关资源
      最近更新 更多