萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 自定義字體完整指南:單控件應用、全局替換、字體圖標與可變字體

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 定義字體族。

二、全局替換:遞歸遍歷 ViewTree

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 方案。

三、現代方案:Downloadable Fonts (API 26+) / Jetpack Fonts

<!-- 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 動態改顏色大小。
  • XML 使用:android:text="\uf015" (對應 Unicode 碼點)。

六、性能與包體積建議

方案APK 體積增量啟動耗時推薦場景
assets + 代碼設置字體文件大小較高(遍歷View)少量特殊字體、舊版本兼容
res/font + XML字體文件大小低(系統解析)標準應用、API 26+
Downloadable Fonts近乎 0極低大字體文件、多語言、追求體積

根據項目 API 等級、字體數量、包體積預算選擇最適合的方案,並建立字體管理規範避免濫用。

copyright © 萬盛學電腦網 all rights reserved