内存泄漏自定义字体设置自定义字体

42 android android-emulator android-intent android-layout 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;
    }
    }
Run Code Online (Sandbox Code Playgroud)

bri*_*tzl 112

您应该缓存TypeFace,否则您可能会冒旧内存泄漏的风险.缓存也会提高速度,因为从资产中读取数据并不是非常快.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我给出了一个关于如何加载自定义字体和样式文本视图作为类似问题的答案完整示例.您似乎正在做大部分工作,但您应该按照上面的建议缓存字体.

  • 替换tf = Typeface.createFromAsset(ctx.getAssets(),"fonts /"+ asset); with tf = FontCache.get("fonts /"+ asset,ctx); (7认同)