android - fontFamily 无法在 androidx 上运行

标签 android android-theme android-styles androidx android-fonts

很奇怪为什么 fontFamily 不能在 androidX 上工作。

这是我的代码:

   <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="testing "
        android:textSize="17sp"
        android:fontFamily="@font/iransans"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

上面的代码根本不影响字体,当我将 textview 转换为 app compact 时,它可以工作:
<androidx.appcompat.widget.AppCompatTextView

我想设置我的整个应用程序字体,但它没有按我预期的那样工作:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="android:fontFamily">@font/iransans</item>
</style>

有什么办法可以解决这个问题吗?如何在不为每个 View 设置字体系列的情况下在整个应用程序中使用我的字体?

最佳答案

您可能会遇到 3 件事中的 1 件以上:

  • 您正在设置 android:fontFamily但未设置 fontFamily在你的主题中。确保两者都有:
  • <item name="fontFamily">@font/iransans</item>
    <item name="android:fontFamily">@font/iransans</item>
    
  • 如果您在较旧的 API 级别上运行,则可能会遇到此错误,升级到 androidx.appcompat 依赖项可能会解决问题:

    https://developer.android.com/jetpack/androidx/releases/appcompat#1.1.0-alpha02
  • 如果您在 styles.xml 中定义了任何其他主题,以及您的TextView 的父级正在使用单独的主题,该主题可能优先于 fontFamily View 上的属性(我还没有确定原因,但这是我自己遇到的情况)。设置android:theme直接在我的TextView上定义字体系列的样式就可以了。
  • <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:theme="@style/MyCustomFontTextAppearance" />
    

    在样式.xml 中:
    <style name="MyCustomFontTextAppearance" parent="TextAppearance.AppCompat.Body1">
        <item name="fontFamily">@font/iransans</item>
        <item name="android:fontFamily">@font/iransans</item>
    </style>
    

    关于android - fontFamily 无法在 androidx 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58592939/

    相关文章:

    android - Android 按钮的圆角 + 背景颜色动态设置?

    Android 风格 - @style、android :, @android :style, 等之间的区别

    android - 在 Android 中何时使用 AsyncTask 和何时使用 Thread

    Android webrequest简单解决方案

    java - Android canvas 不在我的位图上绘制文本

    android - 如何在 Eclipse 中更改应用程序主题

    android - 如何设置全局应用程序背景颜色?

    android - 使用 PNG 图像的 SplashScreen 导致 Android.Views.InflateException,然后是 OutOfMemory

    android - 将自定义小部件样式添加到应用程序主题

    android - Material 设计 : Where to place elevation in android styles?