Android O XML中使用字体
2017/9/25 20:14:35
Android 8.0 推出一项新功能,即 XML 中的字体,允许您使用字体作为资源。这意味着,不再需要以资产的形式捆绑字体。字体在 R 文件中编译,并且作为一种资源,可自动用于系统。然后,您可以利用一种新的资源类型 font 来访问这些字体。
在运行 API 版本 14 及更高版本的设备中,支持库 26 对此功能提供完全支持。(来自官方文档)
效果

实现步骤
在res下新建font文件夹

在font文件夹中添加字体

在XML布局中引用(@font)
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/aayuanqimanman"
android:text="床前明月光,疑是地上霜。
举头望明月,低头思故乡。"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
还可以定义一组字体文件设定样式
在font文件夹下新建资源文件


资源文件
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:font="@font/aayuanqimanman"
android:fontStyle="normal"
android:fontWeight="100" />
<font
android:font="@font/aayuanqimanman"
android:fontStyle="italic"
android:fontWeight="100" />
</font-family>
android:fontStyle 两个属性
normal(正常)
italic(斜体)
可以在面板中选择操作字体属性

style.xml 设置
<style name="myfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily" tools:targetApi="jelly_bean">@font/a_font</item>
</style>
编程操作
只用getFont()方法获取字体资源标识
使用setTypeface()设置字体
Typeface typeface = getResources().getFont(R.font.a_font);
tv_1.setTypeface(typeface);
为了兼容低版本必须声明两组属性
<?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>
检索字体资源使用
ResourcesCompat.getFont()
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
介绍Android 8.0新增的XML字体资源功能,包括如何在项目中添加字体文件,通过XML布局引用字体资源,以及如何在代码中动态设置字体。

356

被折叠的 条评论
为什么被折叠?



