Android O推出了一项新的功能「Fonts in XML」,借助这项功能,我们能够像使用其他资源文件一样使用字体,比较方便地实现App全局字体的替换。
为了能够在API 14或者以上的设备上使用Fonts in XML特性,我们需要使用到Support Library 26。更多的内容可以参考「使用Support Library」小节。
在Android Studio中按照如下步骤将字体作为资源文件添加至工程:
app / res
文件夹,然后选择 New > Android resource directory
。font
,输入 font
作为File name,点击OK
。注意名称字体资源文件夹的名称必须为font
res / font
文件夹中。Android O支持 .otf(OpenType)
和 .ttf(TrueType)
两种格式的字体文件。
在Android Studio中创建Font family的步骤如下:
res / font
文件夹,然后选择 New > Font resource file
。OK
.给TextView添加字体
Properties
窗口,设置TextView的字体:Properties
窗口textAppearance
,选择fontFamily表中的一种字体类型。添加字体至style
打开 style.xml
文件,将fontFamily属性设置为你想要访问的字体文件。
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/lobster</item>
</style>
在你的App的Theme中配置此属性即可实现整个App的字体替换。
Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);
当我们通过 Support Library
实现 Fonts in XML
特性时,需要使用 app
命名空间。Support Library目前支持API 14及以上。
在Android Support Library 26.0-beta1中,必须同时使用android和app命名空间进行声明,以确保在Android O版本及以下设备上字体能够被正确加载。
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<font android:fontStyle="normal" android:fontWeight="400" android:font="@font/myfont-Regular"
app:fontStyle="normal" app:fontWeight="400" app:font="@font/myfont-Regular"/>
<font android:fontStyle="italic" android:fontWeight="400" android:font="@font/myfont-Italic"
app:fontStyle="italic" app:fontWeight="400" app:font="@font/myfont-Italic" /
</font-family>
通过代码控制:
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
内容均来自Android Developer官网,做了简单的翻译,水平有限,还请见谅,原地址: https://developer.android.com/preview/features/fonts-in-xml.html
参考: https://developer.android.com/preview/features/working-with-fonts.html
更多内容:
另外,我在我的开源项目 TonnyL/PaperPlane 中使用 Fonts in XML
实现了App的字体的整体替换。效果如下:
扫码关注腾讯云开发者
领取腾讯云代金券
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. 腾讯云 版权所有