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

标签 android android-layout android-intent android-emulator android-listview

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

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/

相关文章:

Android 布局权重不适用于相对布局

android - 通过 Intent 额外通过电子邮件发送图像时发生 transactiontoolargeException

android - 如何在 Android 中为对齐的组件添加边距

android - 如何以适当的方式缩放 View/ViewGroup - 动 Canvas 局?

android - 监视 Android 服务中的文件夹

android - dimens.xml 中的尺寸是我们在那里看到的吗?

android - 一个按钮有阴影,两个没有 : I cannot tell why

android - 某些设备上的 android 中的 "no such table"问题

android - UIL - ImageAware 被重新用于另一个图像。任务被取消

java - Firebase 身份验证要求更新 Google Play 服务