我在我的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" />
答案 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