首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 全域字體更換指南:一行代碼搞定全 App

     編輯:程式設計疑難解答

想要為 Android App 統一更換字體,卻不想在每個 TextView、Button 逐個設定?這篇文章教你用最簡單的方式,透過自定義 Theme 或 Application 類,一次性套用全域字體,省時又好維護。

核心思路:統一在 Theme 或 Application 設定

Android 提供了多種全域字體替換方案,主流做法有兩種:

  1. 自定義 Theme + fontFamily(API 26+ 原生支援,舊版需搭配 Calligraphy 或 TypefaceSpan)
  2. 在 Application 類中反射替換系統字體映射(相容性最好,但用到隱藏 API,Android P 後受限)

方案一:使用 Android 8.0 (API 26) 以上原生 XML 字體

<!-- res/font/my_font.xml -->
<font-family xmlns:android="https://schemas.android.com/apk/res/android">
    <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/my_regular" />
    <font android:fontStyle="italic" android:fontWeight="400" android:font="@font/my_italic" />
</font-family>

<!-- res/values/styles.xml -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:fontFamily">@font/my_font</item>
</style>

在 AndroidManifest.xml 的 <application> 標籤套用 android:theme="@style/AppTheme" 即可全域生效。

方案二:Calligraphy 庫(舊專案常用,現已停止維護)

// build.gradle
implementation "uk.co.chrisjenx:calligraphy:2.3.0"

// Application 類
@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
        .setDefaultFontPath("fonts/my_font.ttf")
        .setFontAttrId(R.attr.fontPath)
        .build());
}

// BaseActivity
@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

方案三:AndroidX Core Library (API 14+ 相容)

使用 androidx.core:core-ktx 提供的 TypefaceCompat 搭配自定義 TextView 或 ViewFactory,可在不依賴第三方庫的情況下實現相容性較好的全域字體。

避坑指南

  • 字體檔案置於 res/font/ (API 26+) 或 assets/fonts/ (舊方案)。
  • 注意授權問題,商業專案請使用可商用字體(如思源黑體、Noto Sans TC)。
  • WebView、系統對話框、通知欄等非 View 系統元件不受全域字體影響,需單獨處理。

總結

新專案首選原生 fontFamily + XML 字體資源,簡單標準且效能最佳;舊專案維護可暫用 Calligraphy 或自行封裝 BaseActivity 統一處理。避免逐個控件設定,才是正確的架構思維。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved