Android 系統僅內建 sans/serif/monospace 三種字體,滿足品牌設計需求通常需引入自定義字體(.ttf/.otf)。本文涵蓋 單 TextView 應用、全局遞歸替換、FontProvider/Downloadable Fonts、可變字體 及 字體圖標 方案,並對比性能與包體積影響。
// 1. 將字體文件放入 src/main/assets/fonts/ 目錄
// 2. 代碼動態設置
TextView tv = findViewById(R.id.tv_custom);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/DroidSansThai.ttf");
tv.setTypeface(tf);
XML 靜態聲明 (API 26+):
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/my_custom_font"
android:text="Hello" />
需在 res/font/my_custom_font.ttf 放置字體,並配置 fonts.xml 定義字體族。
public class FontManager {
public static void applyFont(ViewGroup root, Context context, String fontPath) {
Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
applyFontRecursive(root, tf);
}
private static void applyFontRecursive(ViewGroup parent, Typeface tf) {
for (int i = 0; i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
if (child instanceof TextView) {
((TextView) child).setTypeface(tf);
} else if (child instanceof Button) {
((Button) child).setTypeface(tf);
} else if (child instanceof EditText) {
((EditText) child).setTypeface(tf);
} else if (child instanceof ViewGroup) {
applyFontRecursive((ViewGroup) child, tf);
}
}
}
}
// 使用:在 BaseActivity.onCreate() 中調用
FontManager.applyFont((ViewGroup) findViewById(android.R.id.content), this, "fonts/xxx.ttf");
缺點: 遞歸遍歷所有 View 會增加啟動耗時,大型介面建議改用 Calligraphy 庫或 XML fontFamily 方案。
<!-- res/font/my_font.xml -->
<font-family xmlns:app="https://schemas.android.com/apk/res-auto"
app:fontProviderAuthority="com.google.android.gms.fonts"
app:fontProviderPackage="com.google.android.gms"
app:fontProviderQuery="Roboto"
app:fontProviderCerts="@array/com_google_android_gms_fonts_certs">
</font-family>
優勢:不增加 APK 體積、系統自動緩存、多 App 共享字體文件。
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/VariableFont.ttf");
// 動態調整粗細 100~900
Typeface variable = tf.createWeightState(new int[]{600});
textView.setTypeface(variable);
IconFont (如 FontAwesome、Material Icons) 以文字形式渲染圖標。textColor/textSize 動態改顏色大小。android:text="\uf015" (對應 Unicode 碼點)。| 方案 | APK 體積增量 | 啟動耗時 | 推薦場景 |
|---|---|---|---|
| assets + 代碼設置 | 字體文件大小 | 較高(遍歷View) | 少量特殊字體、舊版本兼容 |
| res/font + XML | 字體文件大小 | 低(系統解析) | 標準應用、API 26+ |
| Downloadable Fonts | 近乎 0 | 極低 | 大字體文件、多語言、追求體積 |
根據項目 API 等級、字體數量、包體積預算選擇最適合的方案,並建立字體管理規範避免濫用。