45

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

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

2 回答 2

120

您应该缓存 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;
    }
}

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

于 2013-06-03T17:35:26.640 回答
2

我觉得不需要使用字体缓存。我们可以这样做吗?

对上述代码稍作更改,如果我错了,请纠正我。

public class FontTextView extends TextView {
    private static final String TAG = "FontTextView";
    private static Typeface mTypeface;

    public FontTextView(Context context) {
        super(context);
    }

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getAssets(),   GlobalConstants.SECONDARY_TTF);
        }
        setTypeface(mTypeface);
    }

    }
于 2015-09-11T13:05:56.883 回答