Memory leaks with custom font for set custom font(用于设置自定义字体的自定义字体的内存泄漏)
问题描述
以下用于设置自定义字体的代码会降低我的整个应用程序的速度.如何修改它以避免内存泄漏并提高速度和管理内存?
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.
这篇关于用于设置自定义字体的自定义字体的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于设置自定义字体的自定义字体的内存泄漏
基础教程推荐
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01