Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

為整個 App 換字型:Android 四大替換方案

編輯:關於 Android 程式設計

要讓 App 整體換上自訂字型,實務上常見四種做法,從最底層的反射替換,到最直觀的自訂 View,各有適用場景與風險。

方案一:反射替換系統字型(一勞永逸,但有風險)

Typeface 類別內部用幾個 static 欄位快取系統字型。透過反射把它們換掉,全 App 的文字都會跟著變。

public final class FontsOverride {

    public static void setDefaultFont(Context context, String staticTypefaceFieldName,
                                      String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    protected static void replaceFont(String staticTypefaceFieldName, final Typeface newTypeface) {
        try {
            final Field staticField = Typeface.class.getDeclaredField(staticTypefaceFieldName);
            staticField.setAccessible(true);
            staticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

接著在自訂的 Application 裡執行替換:

public final class App extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
        FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
        FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
        FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
    }
}

這個做法很誘人,但它依賴 Typeface 的內部實作細節,不同 Android 版本欄位名稱可能改變,升級系統後有機會失效,因此不建議用在需要長期維護的專案上。

方案二:在主題裡指定 typeface

最省力的方式,但只能從系統內建字型中挑選。

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <item name="android:typeface">monospace</item>
</style>

方案三:遍歷 ViewGroup 逐一設定

從根 View 開始遞迴往下找,遇到 TextView 就套字型;若子 View 是自訂控件且有 setTypeface 方法,也能用反射處理。

/**
 * 遞迴地為 ViewGroup 底下所有 TextView 設定字型
 */
public static final void setAppFont(ViewGroup mContainer, Typeface mFont, boolean reflect) {
    if (mContainer == null || mFont == null) return;

    final int mCount = mContainer.getChildCount();
    for (int i = 0; i < mCount; ++i) {
        final View mChild = mContainer.getChildAt(i);
        if (mChild instanceof TextView) {
            ((TextView) mChild).setTypeface(mFont);
        } else if (mChild instanceof ViewGroup) {
            setAppFont((ViewGroup) mChild, mFont, reflect);
        } else if (reflect) {
            try {
                Method mSetTypeface = mChild.getClass().getMethod("setTypeface", Typeface.class);
                mSetTypeface.invoke(mChild, mFont);
            } catch (Exception e) {
                // 忽略不支援的控件
            }
        }
    }
}

呼叫方式:

final Typeface mFont = Typeface.createFromAsset(getAssets(), "fonts/MyFont.ttf");
final ViewGroup mContainer = (ViewGroup) findViewById(android.R.id.content).getRootView();
setAppFont(mContainer, mFont, true);

注意:這個方法只對當下的 View 樹有效。RecyclerView 或 ListView 捲動後新建立的 item 不會被套用,因此更適合搭配方案四使用。

方案四:自訂 TextView(最可控)

寫一個繼承 TextView 的子類別,在 init 裡指定字型,之後版面檔直接換標籤名稱即可。

public class CusFntTextView extends TextView {

    public CusFntTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public CusFntTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CusFntTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Futura.ttf");
            setTypeface(tf);
        }
    }
}
<com.packagename.CusFntTextView
    android:id="@+id/tvtitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hi Android"
    android:textAppearance="?android:attr/textAppearanceLarge" />

該選哪一個?

需要快速驗證視覺效果,用方案二;頁面數量不多且結構固定,方案三最省事;長期維護的專案,方案四最穩,雖然要改版面檔,但行為可預期、可除錯。另外別忘了 isInEditMode() 的判斷,否則 Layout Editor 預覽會因為找不到字型而當掉。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved