工具类
/************************************************************
* 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();
}
}
}
工具类使用
FontsApplication中代码
public class FontsApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//设置全局默认字体样式
FontsUtils.setDefaultFont(this, "SERIF", "fonts/FZLTXHJW.TTF");
}
}