問題描述
以下用于設置自定義字體的代碼會降低我的整個應用程序的速度.如何修改它以避免內存泄漏并提高速度和管理內存?
The following code for setting custom fonts slows down my whole app. how do i modify it to avoid memory leaks and increase the speed and manage memory well?
public class FontTextView extends TextView {
private static final String TAG = "FontTextView";
public FontTextView(Context context) {
super(context);
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public FontTextView(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.FontTextView);
String customFont = a.getString(R.styleable.FontTextView_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(),"fonts/"+ asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
推薦答案
你應該緩存 TypeFace,否則 你可能會冒著舊手機內存泄漏的風險.緩存也會提高速度,因為從資源中讀取并不是非常快.
You should cache the TypeFace, otherwise you might risk memory leaks on older handsets. Caching will increase speed as well since it's not super fast to read from assets all the time.
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<String, Typeface>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if(tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
}
catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
我提供了一個完整示例,說明如何加載自定義字體和樣式文本視圖作為類似問題的答案.您似乎大部分都做對了,但您應該按照上面的建議緩存字體.
I gave a full example on how to load custom fonts and style textviews as an answer to a similar question. You seem to be doing most of it right, but you should cache the font as recommended above.
這篇關于用于設置自定義字體的自定義字體的內存泄漏的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!