android默认字体(typeface)有三种:snas、serif、monospace,我们要做的就是替换掉其中一种或几种
1、将下载好的ttf文件放到 assets/fonts下
2、工具类FontUtils
//设置新的字体样式
public static void setDefaultFont(Context context, StringstaticTypefaceFieldName, String fontAssetName) {
final Typeface regular =Typeface.createFromAsset(context.getAssets(),fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
//代替原来的文本样式
protected static void replaceFont(String staticTypefaceFieldName, finalTypeface newTypeface) {
Log.i("yyy",staticTypefaceFieldName+","+newTypeface.getStyle());
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、下style中设置
<style name="AppTheme"parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particularAPI-level can go here. -->
<itemname="android:typeface">serif</item>
</style>
<application
android:name="com.example.androidstudy.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >...</application>
4、在Application中使用
FontUtils.setDefaultFont(this, "SERIF","fonts/icomoon.ttf");
我们现在是替换的serif字体,sans好像是默认字体不能替换