【发布时间】: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