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

时间:2017-12-14 22:28:10

标签: android android-theme android-styles android-fonts

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

看起来在我的应用基础主题中设置textViewStylefontFamily,是否会覆盖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" />

1 个答案:

答案 0 :(得分:9)

查看的样式属性优先于textAppearance。

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

因此,不需要在样式中设置基本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