这是为将来遇到与我相同的问题的人准备的。在加载多行时,设置字体往往会占用大量内存。将以下两个代码一起使用,实际上可以使其顺利运行。我从 stackoverflow 得到了解决方案,但他们的答案没有一起列出。
public class RobotoTextView extends TextView {
Context context;
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public RobotoTextView(Context context) {
super(context);
this.context = context;
}
public void setTypeface(Typeface tf, int style) {
if (!isInEditMode()) {
if (style == Typeface.NORMAL) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-Light.ttf"));
} else if (style == Typeface.ITALIC) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-LightItalic.ttf"));
} else if (style == Typeface.BOLD) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-Bold.ttf"));
} else if (style == Typeface.BOLD_ITALIC) {
super.setTypeface(TypeFaceProvider.getTypeFace(getContext(), "fonts/Roboto-BoldItalic.ttf"));
}
}
}
public class TypeFaceProvider {
private static Hashtable<String, Typeface> sTypeFaces = new Hashtable<String, Typeface>(
4);
public static Typeface getTypeFace(Context context, String fileName) {
Typeface tempTypeface = sTypeFaces.get(fileName);
if (tempTypeface == null) {
tempTypeface = Typeface.createFromAsset(context.getAssets(),
fileName);
sTypeFaces.put(fileName, tempTypeface);
}
return tempTypeface;
}
}