系統預設的字型永遠是最安全的選擇,卻也最沒有個性。當品牌需要一致的視覺語彙,或者產品要走向多語言市場時,把自家人打包進 App 裡就成了必經之路。Android 對這件事的支援其實很直接:把字型檔當成資源放進 assets,再用 Typeface 取出來套到控制項上。
在專案根目錄建立 assets/fonts/,把 xxx.ttf 丟進去。這裡要注意,assets 和 res 是兩套不同的機制:assets 裡的檔案不會被編進 R.java,所以程式碼中必須用相對路徑字串「fonts/xxx.ttf」來指路,而不是資源 ID。
與其把載入字型的程式碼散落在各個 Activity 裡,不如集中成一個工具類。寫法是自己寫一個 FontManager,提供 changeFonts() 方法,傳入頁面的根容器與 Activity 本身,它就會沿著 View 樹往下走,把每一個能顯示文字的控制項都換上新的字型。
package arui.www.linuxidc.com;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FontManager {
public static void changeFonts(ViewGroup root, Activity act) {
Typeface tf = Typeface.createFromAsset(act.getAssets(), "fonts/xxx.ttf");
for (int i = 0; i < root.getChildCount(); i++) {
View v = root.getChildAt(i);
if (v instanceof TextView) {
((TextView) v).setTypeface(tf);
} else if (v instanceof Button) {
((Button) v).setTypeface(tf);
} else if (v instanceof EditText) {
((EditText) v).setTypeface(tf);
} else if (v instanceof ViewGroup) {
changeFonts((ViewGroup) v, act);
}
}
}
}
在 onCreate() 完成 setContentView() 之後,把該頁面的根 View 找出來,交給 changeFonts() 即可。因為方法接受的是 ViewGroup,任何容器(LinearLayout、RelativeLayout、FrameLayout……)都能直接傳入。
instanceof TextView 就已經把它攔下來了;保留分開的寫法只是為了閱讀上的清楚。createFromAsset 會反覆讀檔,頁面多、控制項多時開銷明顯。實務上會把 Typeface 存成靜態成員,只載入一次。setTypeface 只替換字型家族,原本透過 setTextSize() 或 style 設定的粗斜體仍需要一併處理。