Android实现全局替换字体

2021-06-19  本文已影响0人  itfitness

目录

效果展示

原生替换字体
WebView本地网页替换字体

实现步骤

原生替换字体
1.创建MyApplication并在AndroidManifest中引用

<application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".WebViewActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

2.自定义application的theme设置默认字体为monospace

   <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <!--    设置默认字体为monospace    -->
        <item name="android:typeface">monospace</item>
    </style>

3.在MyApplication中利用反射替换字体

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        changeTTF();
    }

    private void changeTTF() {
        Typeface typefaceALTAN = Typeface.createFromAsset(getAssets(), "fonts/ALTAN.TTF");
        try {
            Field typefaceField = Typeface.class.getDeclaredField("MONOSPACE");
            typefaceField.setAccessible(true);
            typefaceField.set(null,typefaceALTAN);
        }catch (Exception e){}
    }
}

本地网页替换字体
在样式中定义字体,然后将所有标签的字体改为自己定义的那个即可

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            @font-face {
                font-family:'ALTAN';
                src: url("file:///android_asset/fonts/ALTAN.TTF");
            }
            *{
                font-family: 'ALTAN';
            }
        </style>
    </head>
    <body>
        <p>Hello World</p>
        <h1>Hello World</h1>
    </body>
</html>

最后要注意这里的字体文件和本地网页都放在了assets文件夹下


案例源码

https://gitee.com/itfitness/change-ttf

上一篇 下一篇

猜你喜欢

热点阅读