Android 如何使用本地字体文件

Android 如何使用本地字体文件

hash070 1,765 2022-07-12

本篇文章用于记录如何在Android中加载本地otf、ttf等字体文件。

在布局文件中直接引用本地字体

  1. 在res目录下面 创建 font 字体文件夹,并把我们要用的字体方进去。

image-20220712121710693

  1. res/values/themes.xml文件下配置Style(可选)

这里我们可以定义一个引用了相关字体的Style,把字体的引用规则封装到这个Style中,到时候直接在布局文件里面调用就行了。

    <style name="Regu_Noto">
        <item name="android:fontFamily">@font/noto_regu</item>
    </style>
    <style name="Regu_Noto_Thin">
        <item name="android:fontFamily">@font/noto_thin</item>
    </style>
  1. 在布局文件中调用

使用style="@style/[Style名称]"来调用Style

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:text="@string/welcome_msg"
        android:textSize="20dp"
        android:textColor="@color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo_icon"
        style="@style/Regu_Noto_Thin"/>

也可以使用android:fontFamily="@font/[字体文件名称]"的方法来调用

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:text="@string/welcome_msg"
        android:textSize="20dp"
        android:textColor="@color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo_icon"
        android:fontFamily="@font/noto_thin"/>

在代码中动态更改字体

除了直接在布局文件中直接指定字体,我们还可以在代码中动态设置字体。

第一步,把字体文件放到项目的资源目录下。
本次练习中,我将字体文件放到src/main/assets目录下。注意Android studio项目默认没有assets目录,可以通过右键点击main目录,然后选择New -> Folder -> Assets Folder新建assets目录。
新建的assets目录和java,res目录在同一级。
image-20220712122846140

第二步,在代码中动态设置:

TextView textView = (TextView) view.findViewById(R.id.fragment_text);
Typeface type = Typeface.createFromAsset(view.getContext().getAssets(), "NotoSansHans-Regular.otf");
textView.setTypeface(type);

如上,textView即为我们要更改字体的文本,NotoSansHans-Regular.otf是已经放好的字体文件。

参考文章:

https://blog.csdn.net/u011656025/article/details/112802591

https://blog.csdn.net/qq_35153556/article/details/106620297

https://blog.csdn.net/u010229714/article/details/51647397