一、前言
在以往的开发中,开发者都是将字体文件放在assets
目录下,在程序运行时加载并设置到TextView
中,自从Android 8.0(API level 26)开始,支持将字体文件放在res
资源中,添加XML字体配置,可以在layout
布局文件中直接使用。
PS: 说到这,肯定又有人在想Android 8.0(API level 26)才开始有,这个适配性差。放心,Google早已经考虑到这一点,提供了支持库(需要26及以上版本),可以在Android 4.1 (API level 16)及以上系统上使用这新颖的做法。
二、XML字体配置
需要在XML中引用字体文件,那么就需要将字体文件放到项目的res
资源目录下,这些字体文件会被编译到R.java
文件中,作为资源被引用。font
是在Android 8.0开始的一种新的资源类型。
- 在
res
目录下新建font
目录(如果是使用AndroidStudio,在res
目录下右键,New > Android resource directory,然后选择类型为font
);
- 将字体文件拷贝到
res/font
目录下(字体命名规则要符合Android资源文件命名规则,如果在AndroidStudio中,双击字体可以预览字体);
- 引用字体文件。
2.1 创建字体系列(font family)
字体系列(font family)是拥有自己样式和权重的字体集合。在Android中,你可以通过XML资源创建一个新的字体系列,并当做单独的资源来访问。相比单独引用字体资源并设置每个字体的样式和权重的做法,使用字体系列,系统能够根据文本的样式更准确地选择你想要使用的字体。
- 在资源目录
res/font
下新建XML文件;
- 在新建的XML文件中,添加
<font-family>
根节点,并在根节点内部添加<font>
节点,引用字体文件并配置属性。
<?xml version="1.0" encoding="utf-8"?>
<font-family>
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/cooper_black_std" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/cooper_black_std_italic" />
</font-family>
2.2 在XML中使用字体资源
在XML中TextView
或者它的样式声明中,可以通过fontFamily
属性引用字体资源,包括单独的字体和字体系列。
如果使用字体系列,TextView
会根据实际情况需要,自动切换字体系列中声明的字体。
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="@font/copper_black_std_family"/>
-
在样式声明中使用字体资源
在values/styles.xml
中添加样式声明,并添加android:fontFamily
属性
style name="copperBlackStdFontStyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/copper_black_std_family</item>
</style>
2.3 在编码中使用字体资源
在代码中,通过调用Resources
对象的getFont(int)
方法并传入字体资源唯一id进行获取,这个方法返回Typeface
类型对象,通过调用TextView
的setTypeface(Typeface)
方法设置字体,当然,你也可以使用setTypeface(Typeface, int)
方法设置特定样式的字体。
说明:如果使用的是字体系列,TextView
会自动选择样式。
val typeface = resources.getFont(this, R.font.copper_black_std_family)
tvMsg.typeface = typeface
2.4 使用支持库实现
-
支持库实现XML字体配位置
使用支持库实现XML字体,在XML字体配置上,跟上面提到的差不多,在创建字体系列时,需要引入命名空间才能使用。
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
<font
app:fontStyle="normal"
app:fontWeight="400"
app:font="@font/cooper_black_std" />
<font
app:fontStyle="italic"
app:fontWeight="400"
app:font="@font/cooper_black_std_italic" />
</font-family>
-
在代码中引用字体资源
在低于Android 8.0(API level 26)中,Resources
中没有getFont(int)
方法,那么需要通过支持库提供的API获取字体资源,那就是ResourcesCompat.getFont(int)
,除此之外,其他的都一致。
val typeface = ResourcesCompat.getFont(this, R.font.copper_black_std_family)
tvMsg.typeface = typeface