替换字体也是一个比较常见的需求,一般分几种情况。实现起来也不麻烦,这里简单记录下
assets目录下拷贝字体文件
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();
}
}
新增主题
<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);
END
点亮【赞和在看】,让钱和爱都流向你。
心里种花,人生才不会荒芜,如果你也想一起成长,请点个关注吧。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有