如何在 XML 中使用指定字体权重

84
使用XML中的字体功能,您可以为字体系列指定各种字重。例如:
<?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:font="@font/archivo_narrow_regular" android:fontWeight="400" android:fontStyle="normal"
        app:font="@font/archivo_narrow_regular" app:fontWeight="400" app:fontStyle="normal"/>

    <font android:font="@font/archivo_narrow_regular_italic" android:fontWeight="400" android:fontStyle="italic"
        app:font="@font/archivo_narrow_regular_italic" app:fontWeight="400" app:fontStyle="italic"/>

    <font android:font="@font/archivo_narrow_medium" android:fontWeight="500" android:fontStyle="normal"
        app:font="@font/archivo_narrow_medium" app:fontWeight="500" app:fontStyle="normal"/>

    <font android:font="@font/archivo_narrow_medium_italic" android:fontWeight="500" android:fontStyle="italic"
        app:font="@font/archivo_narrow_medium_italic" app:fontWeight="500" app:fontStyle="italic"/>

    <font android:font="@font/archivo_narrow_semibold" android:fontWeight="600" android:fontStyle="normal"
        app:font="@font/archivo_narrow_semibold" app:fontWeight="600" app:fontStyle="normal"/>

    <font android:font="@font/archivo_narrow_semibold_italic" android:fontWeight="600" android:fontStyle="italic"
        app:font="@font/archivo_narrow_semibold_italic" app:fontWeight="600" app:fontStyle="italic"/>

    <font android:font="@font/archivo_narrow_bold" android:fontWeight="700" android:fontStyle="normal"
        app:font="@font/archivo_narrow_bold" app:fontWeight="700" app:fontStyle="normal"/>

    <font android:font="@font/archivo_narrow_bold_italic" android:fontWeight="700" android:fontStyle="italic"
        app:font="@font/archivo_narrow_bold_italic" app:fontWeight="700" app:fontStyle="italic"/>

</font-family>

但我无法弄清楚如何实际使用这些字重;无论是在XML(布局/样式)文件中还是在Java代码中。对于TextView,没有可用的fontWeight属性,从ResourcesCompat.getFont(context, R.font.archivo_narrow)创建的Typeface对象没有提到字重。

我意识到我可以指定特定的字体资源(即R.font.archivo_narrow_semibold),但那么在font-family中有fontWeight属性的意义是什么?


更新

在 API Level 28 中新增了一个静态的 create(Typeface family, int weight, boolean italic) 方法,以及一个 getWeight() 实例方法。这终于使得在 Java 代码中可以使用 fontWeight 属性;尽管只适用于 API Level 28 及以上版本,我没有在支持库中找到任何类似的功能。

这很有用,也表明过去的 fontWeight 属性没有任何作用,但我真的很想能够在 XML 样式中使用该权重。


1
我看到问题中的更新,但我认为它实际上应该是一个答案,因为它提供了比当前任何答案都更好的答案。 - arekolek
2
在28以下的区间,字体粗细用于区分普通和加粗。 - Florian Walther
1
你尝试过使用 textFontWeight XML 属性吗?即使在 API 28 上,它对我也不起作用。 - Florian Walther
11个回答

-2
请参考官方Android字体重量值文档:
android:fontWeight
整数。字体的重量。当字体被加载到字体堆栈中时,此属性用于覆盖字体头表中的任何重量信息。属性值必须是正数、100的倍数,且在100至900之间(包括100和900)。如果您没有指定该属性,则应用程序将使用字体头表中的值。最常见的值为400表示普通字体,700表示粗体。

https://developer.android.com/guide/topics/resources/font-resource


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接