您现在的位置是:首页 > 文章详情

andorid 修改字体一文搞定

日期:2019-06-23点击:361

本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点

替换字体也是一个比较常见的需求,一般分几种情况。实现起来也不麻烦,这里简单记录下

全局替换字体

步骤1

assets目录下拷贝字体文件

步骤2

application中替换默认字体

在Application的onCreate方法中增加替换方法

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

步骤3:新增主题Theme,并在AndroidManifest文件中注册

新增主题

<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目录,拷贝字体文件

步骤2: 代码中替换

TextView textView = (TextView) findViewById(R.id.textView_font); Typeface typeface = ResourcesCompat.getFont(this, R.font.myfont); textView.setTypeface(typeface);

 欢迎关注我的微信公众号,和我一起每天进步一点点!

AntDream

原文链接:https://yq.aliyun.com/articles/706374
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章