关于字体设置的属性及替换方式,可以参考如下文章:
android:fontFamily
指定字体- @font/noto_sans_sc
完成上一步之后,对应的Activity,包括其中弹出的Dialog中的文本的字体就已经更改了,但是实践中有一些其他情况需要处理。
使用自定义Toast,然后设置其中 TextView 的字体
Typeface font = null;
try {
font = ResourcesCompat.getFont(context, sCustomFontResId);
} catch (Resources.NotFoundException ignore) {
Log.e("ToastUtils", "customFont not found: " + sCustomFontResId);
}
if (font != null) {
view.setTypeface(font);
view.setIncludeFontPadding(false);
}
Toast toast = new Toast(context);
toast.setView(view);
发现使用思源黑体之后,TextView 的垂直边距及行间距出现了问题:
对于上述问题,解决方案如下:
android:includeFontPadding
的配置,将其值设置为 false
部分字体存在多种不同字重,如思源黑体存在7中字重的文件,如果全部加载到内存中,则部分VM内存较小的设备会直接OOM崩溃,故只引入normal字重(400)的字体
需要使用 app 的 namespace 确保向下兼容性
ResourcesCompat.getFont(context, sCustomFontResId)
view.setTypeface(font);
view.setIncludeFontPadding(false);