2013-08-06 23 views
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); 
    } 

} 

回答

1

在您的自定义TextView的做法,正在创建的字样对象每次创建一个CustomTextView(或更改其字体),而你的工厂会将已经加载的文件保存在内存中并重新使用它们。

在某些情况下,使用自定义文本视图的方法可能会正常工作,但如果您突然需要创建很多(或更改许多字体),它可能会显着降低性能,如this question with a scrollview

我会选择单身人士。