Ошибка производительности на пользовательском шрифте TextView
У меня есть пользовательский 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" , и он работает очень хорошо.
Я использую этот TextViewPlus в ListView, заполненный 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 без проблем с производительностью?
Ответы
Ответ 1
Почему бы вам не сохранить созданный объект typface
в памяти, чтобы вы не создавали каждый раз, когда создается текстовое представление.
Ниже приведен пример класса, который создает и кэширует объект шрифта:
public class TypeFaceProvider {
public static final String TYPEFACE_FOLDER = "fonts";
public static final String TYPEFACE_EXTENSION = ".ttf";
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) {
String fontPath = new StringBuilder(TYPEFACE_FOLDER).append('/').append(fileName).append(TYPEFACE_EXTENSION).toString();
tempTypeface = Typeface.createFromAsset(context.getAssets(), fontPath);
sTypeFaces.put(fileName, tempTypeface);
}
return tempTypeface;
}
}