如何在Android EditText中使用自定义字体时提高性能?

时间:2011-12-02 14:56:01

标签: android performance fonts textview android-edittext

我在Android中使用.ttf字体自定义TextView,使用:

Typeface handType = Typeface.createFromAsset ( getContext().getAssets(), "fonts/JOURNAL.TTF");

问题是,当它进入编辑模式时,字符不会像默认的内置字体那样立即出现在屏幕上,但是它们需要一些时间来渲染,短暂但足以让它感觉迟钝。

是否有任何技术(缓存等)可以帮助我立即呈现字体?

同时注意到延迟因字体而异,并且字体复杂性似乎变得最差

1 个答案:

答案 0 :(得分:1)

您可以尝试使用工厂。这真的更好,因为我们不会每次都分配字体。

import java.util.HashMap;

import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;

public class FontFactory {
private static FontFactory instance;
private HashMap<String, Typeface> fontMap = new HashMap<String, Typeface>();
private Context context;

private FontFactory(Context context) {
    this.context = context.getApplicationContext();
}

public static FontFactory getInstance(Context context) {
    if(instance == null){
        return instance = new FontFactory(context);
    } else {
        return instance;
    }
}

public Typeface getFont(String font) {
    Typeface typeface = fontMap.get(font);
    if (typeface == null) {
        try {
            typeface = Typeface.createFromAsset(context.getResources().getAssets(), "fonts/" + font);
            fontMap.put(font, typeface);  
        } catch (Exception e) {
            Log.e("FontFactory", "Could not get typeface: " + e.getMessage() + " with name: " + font);
            return null;
        }

    }
    return typeface;
}

}

要点:https://gist.github.com/odemolliens/4d5ff5630b6317397956

相关问题