所以我已经扩展了 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
的屏幕截图:
几次旋转后的相同屏幕截图如下:
很明显,在每次屏幕旋转时,资产分配和本机堆都会增加(垃圾回收器也无法清除此类情况)。那么,我们肯定不能像上述方式那样使用自定义字体,如果不是这样,我们应该如何使用自定义字体呢?