gpt4 book ai didi

android - 用于设置自定义字体的自定义字体的内存泄漏

转载 作者:IT王子 更新时间:2023-10-28 23:58:20 25 4
gpt4 key购买 nike

以下用于设置自定义字体的代码会降低我的整个应用程序的速度。如何修改它以避免内存泄漏并提高速度和管理内存?

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;
}
}

最佳答案

你应该缓存字体,否则 you might risk memory leaks on older handsets .缓存也会提高速度,因为从资源中读取并不是非常快。

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;
}
}

我给了 full example on how to load custom fonts and style textviews as an answer to a similar question .您似乎大部分都做对了,但您应该按照上面的建议缓存字体。

关于android - 用于设置自定义字体的自定义字体的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16901930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com