我是 android 新手,我想为我的应用程序使用我的自定义字体。我写了两种创建自定义字体的方法。你能告诉我哪一个更好更快。第一种方法是使用单例类第二种方法是创建我自己的文本视图。
单例
public class FontFactory {
private static FontFactory instance;
private HashMap<String, Typeface> fontMap = new HashMap<String, Typeface>();
private FontFactory() {
}
public static FontFactory getInstance() {
if (instance == null){
instance = new FontFactory();
}
return instance;
}
public Typeface getFont(DefaultActivity pActivity,String font) {
Typeface typeface = fontMap.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(pActivity.getResources().getAssets(), "fonts/" + font);
fontMap.put(font, typeface);
}
return typeface;
}
}
有自己的文本视图
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setFonts(context,attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFonts(context,attrs);
}
private void setFonts(Context context, AttributeSet attrs){
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView_customFont);
String ttfName = a.getString(R.styleable.MyTextView_customFont_ttf_name);
setCustomTypeFace(context, ttfName);
}
public void setCustomTypeFace(Context context, String ttfName) {
Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/MuseoSansCyrl_"+ttfName+".otf");
setTypeface(font);
}
@Override
public void setTypeface(Typeface tf) {
super.setTypeface(tf);
}
}