2013-08-06 24 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

我會選擇單身人士。