gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:11:07 26 4
gpt4 key购买 nike

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

它看起来像在我的应用程序基本主题中设置 textViewStylefontFamily,allays 覆盖 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 会从其 Activity 中获取该样式。

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

<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 个 textAppearance:DefaultTextAppearance,用作所有 TextView 的默认值和 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:如何设置应用程序范围的默认字体,而不覆盖 textAppearance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47823085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com