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

时间:2013-06-03 16:57:58

标签: 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;
    }
    }

2 个答案:

答案 0 :(得分:106)

您应该缓存TypeFace,否则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。您似乎正在做大部分工作,但您应该按照上面的建议缓存字体。

答案 1 :(得分:1)

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

对上述代码进行微小更改,如果我错了,请纠正我。

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

    }