Aide学Android开发

android 全局修改系统字体样式

2018-01-11  本文已影响792人  石头1314
效果图对比.png

工具类

/************************************************************
 * Author: ssc
 * Date: 2018/1/11
 * Version: 1.0
 * Description:字体替换工具类
 * History:
 * <author>  <time>   <version >   <desc>
 ***********************************************************/

public class FontsUtils {
    /**
     * 设置自定义字体
     *
     * @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();
        }
    }
}

工具类使用

步骤一和二.png 步骤三.png 步骤四.png

FontsApplication中代码

public class FontsApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //设置全局默认字体样式
        FontsUtils.setDefaultFont(this, "SERIF", "fonts/FZLTXHJW.TTF");
    }
}

上一篇 下一篇

猜你喜欢

热点阅读