2016-08-03 130 views
1

我有一個自定義TextView,我從我的服務器獲取所有文本,所以我不知道什麼風格即將到來。例如,這可以包括bold,italic和更多Textstyles。但我不知道如何在運行時處理它。Textview在運行時更改字體

我創造了我的所有字體的assets文件夾我想用:

enter image description here

在我CustomTextView我想是這樣的:

public class CustomTextView extends TextView { 

private static final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android"; 

public CustomTextView(Context context) { 
    super(context); 

    applyCustomFont(context, null); 
} 

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

    applyCustomFont(context, attrs); 
} 

public CustomTextView(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 

    applyCustomFont(context, attrs); 
} 

private void applyCustomFont(Context context, AttributeSet attrs) { 

    //Workaround for Preview Mode 
    if (!isInEditMode()) { 
     int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL); 

     Typeface customFont = selectTypeface(context, textStyle); 
     setTypeface(customFont); 

    } else { 

     this.setTypeface(null, Typeface.NORMAL); 
    } 
} 

private Typeface selectTypeface(Context context, int textStyle) { 

    switch (textStyle) { 
     case Typeface.BOLD: // bold 
      return FontCache.getTypeface("fonts/OpenSans-Bold.ttf", context); 

     case Typeface.ITALIC: // italic 
      return FontCache.getTypeface("fonts/OpenSans-Italic.ttf", context); 

     default: 
      return FontCache.getTypeface("fonts/OpenSans-Regular.ttf", context); 
    } 
} 

} 

這是我FontCache類:

public class FontCache { 

//This caches the fonts while minimizing the number of accesses to the assets 

private static final HashMap<String, Typeface> fontCache = new HashMap<>(); 

public static Typeface getTypeface(String fontname, Context context) 
{ 
    Typeface typeface = fontCache.get(fontname); 

    if (typeface == null) 
    { 
     try { 
      typeface = Typeface.createFromAsset(context.getAssets(), fontname); 

     } catch (Exception e) { 
      return null; 
     } 

     fontCache.put(fontname, typeface); 
    } 

    return typeface; 
} 

} 

但是t帽子不是如何工作的,任何想法如何做到這一點? 謝謝!

+1

是什麼'FontCache'? – Blackbelt

+0

謝謝,我加了! – Davis

+0

看起來不錯。有什麼問題? – Blackbelt

回答

1

您可以覆蓋setTypeface(Typeface tf, int style)

@Override 
public void setTypeface(Typeface tf, int style) { 
    Typeface customFont = selectTypeface(context, textStyle) 
    super.setTypeface(customFont, style); 
} 

從外面,你可以這樣調用它

mTextView.setTypeface(null, Typeface.BOLD); 
+0

這很有幫助,謝謝! – Davis

+0

不客氣 – Blackbelt