2
我是Android新手,我想爲自己的應用使用自定義字體。我寫了2種創建自定義字體的方法。你能告訴我傢伙哪個更好,更快嗎? 第一種方式是使用單例類第二種方法是創建我自己的textview。創建自定義字體哪一個更好
與單
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;
}
}
與自己的TextView
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);
}
}