gpt4 book ai didi

android - 如何在 .xml 文件而不是 .java 文件中设置自定义字体?

转载 作者:IT老高 更新时间:2023-10-28 22:12:04 27 4
gpt4 key购买 nike

我正在创建一个要在其中设置自定义字体的应用程序。

但我不能在 .xml 文件中使用自定义字体,为此我需要在 .java 文件中初始化每个 TextView。

这个过程太冗长和耗时。

如果有人知道,请帮助我...

最佳答案

Android API 16+

从 Android 8.0 (API 26) 开始,原生支持在 XML 中设置字体。但是,使用支持库将其扩展到 Android 4.1 (API 16)。

enter image description here

1。为您的项目添加字体

  • 右键单击 res 文件夹并转到 New > Android Resource Directory。键入 font 作为名称,键入 font 作为资源类型。
  • 将您的字体复制并粘贴到新的 res/font 目录中。在我的示例中,我只使用了一种字体,即常规 dancing script。字体。我将它重命名为 dancing_script.ttf 只是为了避免大写或非法字符的任何潜在命名问题。

2。创建一个 font-family XML 文件。

  • 右键单击 res/font 文件夹并选择 New > Font Resource File。随心所欲地调用它。我正在调用我的 my_custom_font.xml
  • 粘贴以下代码。请注意,属性设置了两次,一次用于 android (API 26+),一次用于 app (API 16+)。

    <?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/dancing_script"
    app:fontStyle="normal"
    app:fontWeight="400"
    app:font="@font/dancing_script"
    />
    </font-family>

3。在 XML 中设置字体

现在您可以使用 fontFamily 属性来设置 XML 中的字体。

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:fontFamily="@font/my_custom_font" />

注意事项

关于android - 如何在 .xml 文件而不是 .java 文件中设置自定义字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36472953/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com