Утечки памяти с пользовательским шрифтом для установки пользовательского шрифта

Следующий код для установки пользовательских шрифтов замедляет все мое приложение. Как я могу изменить его, чтобы избежать утечек памяти и увеличить скорость и хорошо управлять памятью?

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 ответа

Решение

Вы должны кэшировать 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;
    }
}

Я дал полный пример того, как загрузить пользовательские шрифты и стилизованные текстовые представления в качестве ответа на аналогичный вопрос. Кажется, вы делаете большую часть правильно, но вы должны кэшировать шрифт, как рекомендовано выше.

Я чувствую, что использование кэша шрифтов не нужно. Можем ли мы сделать это так?

Незначительное изменение в приведенном выше коде, поправьте меня, если я ошибаюсь.

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

    }
Другие вопросы по тегам