首页 > 解决方案 > 无法覆盖 AppTheme 字体

问题描述

这是我的 AppTheme 风格style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:fontFamily" tools:targetApi="jelly_bean">@font/montserrat_regular</item>
    <item name="fontFamily">@font/montserrat_regular</item>
</style>

和应用程序标签manifest.xml

 <application
        android:name=".Amelio"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"

我想要的是在 AppTheme 中设置 fontFamily,这样我就不必在应用程序的每个组件上设置它。但我想在应用程序中的一些 TextView 上设置自定义字体。

fontFamily问题是当我设置AppTheme然后我不能设置字体或fontFamily任何TextView。但是当我fontFamilyfont. AppTheme这是预览 -

  1. 带有 AppTheme 风格的字体属性

在 AppTheme 中使用字体

  1. AppTheme 样式中没有字体属性

在 AppTheme 中使用字体

注意:我知道可以使用 font 或 fontFamily,我只是在尝试两者都可以。所以请忽略它。

标签: androidfontsandroid-xml

解决方案


Khemraj 建议https://stackoverflow.com/a/16407123/6891563是正确的,因为当您想要覆盖某些组件的属性时,您需要覆盖其样式,所以当您添加时(取自 Hussein El Feky):

<!-- Into a styles.xml--!>
<style name="RobotoTextViewStyle" parent="android:Widget.TextView">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<!-- Into a themes.xml--!>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:textViewStyle">@style/RobotoTextViewStyle</item>
    <item name="buttonStyle">@style/RobotoButtonStyle</item>
</style>

您正在覆盖所有 TextView 的样式,因此无论何时使用 AppTheme,TextView 组件都会监​​听 RobotoTextViewStyle 属性并使用它们。


推荐阅读