我有一个自定义的TextView,带有个性化字体属性:
public class TextViewPlus extends TextView {
private static final String TAG = "TextViewPlus";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
// This is called all the time I scroll my ListView
// and it make it very slow.
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
setTypeface(tf);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
return true;
}
}
我在我的XML文件中使用它,属性为customFont="ArialRounded.ttf",效果非常好。
我在ListView中使用这个TextViewPlus,用一个ArrayAdapter来填充。
TextViewPlus dataText = (TextViewPlus) itemView.findViewById(R.id.data_text);
dataText.setText("My data String");
我的问题是,当我滚动ListView时,性能非常差!非常缓慢而且充满延迟。每次我滚动列表时,都会调用TextViewPlus构造函数n°2。
如果我将TextViewPlus更改为普通的TextView,并使用dataText.setTypeface(myFont),一切都很顺利,运行良好。
如何使用我的TextViewPlus而没有性能问题?
Typeface
缓存到某个地方,这样它就不需要每次都重新创建了吗? - jprofitt