本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一块儿天天进步一点点android
替换字体也是一个比较常见的需求,通常分几种状况。实现起来也不麻烦,这里简单记录下bash
assets目录下拷贝字体文件微信
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(); } } 复制代码
新增主题布局
<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);
复制代码
欢迎关注个人微信公众号,和我一块儿天天进步一点点!
复制代码