2014-03-25 28 views
3

所以我已經擴展到TextView使用自定義字體(如描述here),即使用自定義的字體在正確的Android

public class CustomTextView extends TextView { 
    public static final int CUSTOM_TEXT_NORMAL = 1; 
    public static final int CUSTOM_TEXT_BOLD = 2; 

    public CustomTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     initCustomTextView(context, attrs); 
    } 

    private void initCustomTextView(Context context, AttributeSet attrs) { 
     TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView, 0, 0); 
     int typeface = array.getInt(R.styleable.CustomTextView_typeface, CUSTOM_TEXT_NORMAL); 
     array.recycle(); 
     setCustomTypeface(typeface); 
    } 

    public setCustomTypeface(int typeface) { 
     switch(typeface) { 
      case CUSTOM_TEXT_NORMAL: 
       Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "customTextNormal.ttf"); 
       setTypeface(tf); 
       break; 
      case CUSTOM_TEXT_BOLD: 
       Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "customTextBold.ttf"); 
       setTypeface(tf); 
       break; 
     } 
    } 
} 

我然後加入到活動的主要佈局的片段使用CustomTextView。所有的工作都很好,但似乎存在一些內存問題,即每次旋轉屏幕(導致活動經歷其生命週期)時,除了之前的加載之外,字體資產都會加載到本地堆中。例如;下面是從adb shell dumpsys meminfo my.package.com屏幕轉儲初始加載後沒有屏幕旋轉(使用的Roboto-Light字體):

enter image description here

,並且在同一屏幕轉儲幾個rotaions後

enter image description here

清楚的是在每個屏幕旋轉上發生的資產分配本地堆的增加(GC不會清除這一點)。當然,我們不應該以上述方式使用自定義字體,如果不是,我們應該如何使用自定義字體?

回答

2

你應該找到你的答案here

基本上你需要建立你自己的系統來創建它們之後緩存這些字體(因此你只會創建每個字體一次)。

+0

看起來不錯,而且合理。 –