項目裡有個需求:程序中要用到好幾套字體(中英各三種),於是去找一條省事的實現路徑。折騰下來,主流做法大致三種:
搜了很久發現,Android 並不支持直接指定 FontFamily 來換字體,著實坑人。倒是有人提出一條野路子:Root 之後把字體複製到 system/Fonts 目錄,再在程序中引用對應的 FontFamily——未經測試,僅供參考。
網上最常見的做法是重寫 TextView。我暫時採用的就是這種方式,透過繼承派生出 TitleTextView、ContentTextView、RemarkTextView 之類的自定義控件,每個類綁定一種字體:
public class TitleTextView extends TextView {
public TitleTextView(Context context) {
this(context, null);
}
public TitleTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TitleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setTypeface(Typeface.createFromAsset(
getResources().getAssets(), "zhongteyuanti.ttc"));
}
}
XML 中直接當普通控件用:
<com.Yokeqi.Controls.TitleTextView
android:id="@+id/tv_login_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="@string/login_title" />
好處是不必替每個 TextView 逐一指定 FontFamily,字體屬性由類自身承載。壞處也極其明顯:吃內存。一個原本不指定字體、約 57MB 的程序,換成這種方式之後居然飆到 440MB 以上,不優化簡直沒法用。
由此衍生出一個 config 的思路:Key-Value 分別是 FontFamily 與 Typeface,再由一個 FontManager 統一管理。利用單例思想保證同一個 FontFamily 只會拿到同一個 Typeface 實例,避免反覆創建帶來的內存損耗。
public static HashMap<String, Typeface> TypefaceMap = new HashMap<String, Typeface>();
public static Typeface getTypefaceByFontName(Context context, String name) {
if (TypefaceMap.containsKey(name)) {
return TypefaceMap.get(name);
} else {
Typeface tf = Typeface.createFromAsset(
context.getResources().getAssets(), name);
TypefaceMap.put(name, tf);
return tf;
}
}
TitleTextView 裡的字體設置隨之簡化為:
this.setTypeface(FontManager.getTypefaceByFontName("zhongteyuanti.ttc"));
進一步擴展:因為程序要按中英兩種語言取不同字體,config 裡還加了語言選項,最終把 config 落成一個放在 Assets 中的 XML,key-value 變成 FontFamily 與字體文件名,FontManager 負責解析它、拿到文件名再取 Typeface。以後要換某個 FontFamily 對應的字體,改配置即可,不必動代碼。
如果控件類型五花八門——除了 TextView,Button、Spinner 也要換字體——那繼承法就照顧不過來了。只能寫一個 initFont() 放到初始化流程裡,把相關控件遍一遍。控件數量不多的情況下,多寫幾行代碼總比實現不了強。這個方法本質上仍然是在設置 Typeface,所以照樣得配合單例緩存,否則內存照樣爆。