andorid 修改字體一文搞定

本文首發於公衆號「AntDream」,歡迎微信搜索「AntDream」或掃描文章底部二維碼關注,和我一塊兒天天進步一點點android

替換字體也是一個比較常見的需求,通常分幾種狀況。實現起來也不麻煩,這裏簡單記錄下bash

全局替換字體

步驟1

assets目錄下拷貝字體文件微信

步驟2

application中替換默認字體markdown

在Application的onCreate方法中增長替換方法app

/**
 * 設置自定義字體
 *
 * @param context
 * @param staticTypefaceFieldName 須要替換的系統字體樣式
 * @param fontAssetName           替換後的字體樣式
 */
public static void setDefaultFont(Context context, String staticTypefaceFieldName, String fontAssetName) {
    // 根據路徑獲得Typeface
    Typeface regular = Typeface.createFromAsset(context.getAssets(), fontAssetName);
    // 設置全局字體樣式
    replaceFont(staticTypefaceFieldName, regular);
}

private 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();
    }
}

複製代碼

步驟3:新增主題Theme,並在AndroidManifest文件中註冊

新增主題佈局

<style name="YourTheme" parent="AppTheme.Base">
    <item name="android:typeface" >serif</item>
</style>

複製代碼

在AndroidManifest.xml文件中設置主題字體

<application xmlns:tools="http://schemas.android.com/tools"
    ...
    android:theme="@style/YourTheme"
    tools:replace="android:theme">
    ...
</application>

複製代碼

替換某些佈局中的字體,也就是局部替換

步驟1:在res目錄下新建font目錄,拷貝字體文件this

步驟2: 代碼中替換spa

TextView textView = (TextView) findViewById(R.id.textView_font);
Typeface typeface = ResourcesCompat.getFont(this, R.font.myfont);
textView.setTypeface(typeface);
複製代碼

歡迎關注個人微信公衆號,和我一塊兒天天進步一點點!
複製代碼

AntDream
相關文章
相關標籤/搜索