编程语言
首页 > 编程语言> > Android:如何设置应用程序范围的默认字体,而不是覆盖textAppearance

Android:如何设置应用程序范围的默认字体,而不是覆盖textAppearance

作者:互联网

我在我的Android应用程序中使用自定义字体.我想将此自定义字体设置为应用程序默认字体(作为后备)但我仍然希望使用TextView textAppearance属性来设置字体和文本样式.

它看起来像在我的应用程序基础主题中设置textViewStyle或fontFamily,覆盖覆盖TextView textAppearance样式?

<style name="MyApp.Base" parent="Theme.AppCompat.Light.NoActionBar">

    <!-- Overriding fontFamily also overrides textView textAppearance -->
    <item name="android:fontFamily">@font/open_sans</item>

    <!-- Overriding textViewStyle also overrides textView textAppearance -->
    <item name="android:textViewStyle">@style/DefaultTextAppearance</item>

</style>

 <style name="DefaultTextAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textStyle">normal</item>
    <item name="fontFamily">@font/open_sans_regular</item>
</style>

<style name="BoldTextAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textStyle">normal</item>
    <item name="fontFamily">@font/open_sans_extra_bold</item>
</style>


<!-- This textView does not get bold style -->
<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Me happy"
  android:textAppearance="@style/BoldTextAppearance" />

解决方法:

View的样式属性更优先于textAppearance.

在这两种情况下,你都有fontFamily里面的样式而不是textAppearance.当您将fontFamily直接放在基本主题中时,view会从其活动中获取该样式.

因此,不需要在样式中设置基本fontFamily值,而是需要设置基TextView的textAppearance:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:textViewStyle">@style/TextViewStyle</item>
</style>

<style name="TextViewStyle" parent="@android:style/TextAppearance.Widget.TextView">
    <item name="android:textAppearance">@style/DefaultTextAppearance</item>
</style>

<style name="DefaultTextAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textStyle">normal</item>
    <item name="fontFamily">@font/roboto_regular</item>
</style>

<style name="LobsterTextAppearance" parent="TextAppearance.AppCompat">
    <item name="android:textStyle">normal</item>
    <item name="fontFamily">@font/lobster</item>
</style>

所以,这里我有2个textAppearances:DefaultTextAppearance,用作所有TextViews和LobsterTextAppearance的默认值,我在特定情况下使用它.

布局看起来像:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Default roboto text" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Lobster text"
    android:textAppearance="@style/LobsterTextAppearance" />

所以,首先TextView使用基础textAppearance的fontFamily,第二个使用重写的@style / LobsterTextAppearance

fontFamily textAppearance preview

标签:android-styles,android-theme,android,android-fonts
来源: https://codeday.me/bug/20190722/1500697.html