TextAppearance 覆盖样式的 fontFamily

时间:2021-04-02 09:56:28

标签: android textview styles material-components-android

我有一个带有自定义 fontFamily 的 TextView 样式。另外,我的 textAppearance 有一个单独的样式。

当我将 TextView 样式和 textAppearance 样式设置为单个 TextView 时,fontFamily 被忽略了。但是当没有 textAppearace 的样式设置时一切正常。

使用来自 airbnb 的 Paris 库设置样式。

TextView 样式:

<style name="TextViewBold" parent="Widget.MaterialComponents.TextView">
    <item name="fontFamily">@font/roboto_bold</item>
    <item name="android:fontFamily">@font/roboto_bold</item>
    <item name="android:textColor">@color/black</item>
</style>

文本外观样式:

<style name="TextAppearanceAllCaps">
    <item name="textAllCaps">true</item>
    <item name="android:textAllCaps">true</item>
    <item name="android:textColor">@color/anotherColor</item>
</style>

以编程方式设置的样式:

MaterialTextView(context!!).apply {
        style(R.style.TextViewBold) //Paris used here
        updateTextAppearance(R.style.TextAppearanceAllCaps) //custom extension
        setText(R.string.some_text)
}

扩展代码:

fun TextView.updateTextAppearance(@StyleRes resId: Int) {
    TextViewCompat.setTextAppearance(this, resId)
}

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:0)

你可以这样做:

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAllCaps="true"
    android:textColor="@color/white"
    android:theme="your theme"
    />

答案 1 :(得分:0)

我建议使用此工作流程来设置文本样式:

  1. 在主题的 textViewStyle 默认样式中设置任何应用范围的样式。

  2. 设置您的应用将使用的(小)TextAppearances 选择(或从 MaterialComponent 的 styles 使用/扩展)并直接从您的视图中引用它们

  3. 创建样式设置 TextAppearance 不支持的任何属性(它们本身指定您的 TextAppearance 之一)。

  4. 直接在您的布局中执行任何独特的样式。

答案 2 :(得分:0)

感谢所有愿意提供帮助的人!

我发现了一个问题和一个解决方案(针对我的具体情况)。在大多数情况下,您可以检查已接受的答案。

问题:

当以编程方式设置 fontFamily 时,样式 textAppearance 属性会被删除。我什至尝试延迟设置我的文本外观,以检查 UI 线程是否没有过载,但这没有帮助。 另外,我尝试在没有巴黎的情况下设置样式,也没有帮助。

顺便说一下,我没有找到原因:(

解决方案:

我只用我的 TextView 元素创建了 XML 文件(感谢 @D_K 的提示)。然后我在 XML 中设置样式和文本外观,并在我需要的地方对其进行扩充。 只有使用这种方法,我才能实现我想要的。

附言如果您对文本颜色有问题,只需在文本视图样式中将其设置为 @null,然后将使用 textAppearance 中的 textColor

答案 3 :(得分:0)

只需从定义了 TextAppearance 的父级继承 fontFamily 或将其添加到您的自定义 TextAppearance 中。

例如:

<style name="TextViewBold" parent="Widget.MaterialComponents.TextView">
   <item name="android:textAppearance">TextAppearance.App</item>
</style>


<style name="TextAppearance.App" parent="TextAppearance.MaterialComponents.Body1">
   <item name="fontFamily">@font/roboto_bold</item>
   <!-- .... -->
</style>

<!-- Inherit from TextAppearance.App -->
<style name="TextAppearance.App.AllCaps"> 
   <item name="textAllCaps">true</item>
</style>

然后将样式 TextView 应用到 @style/TextViewBold 并使用 textAppearance

更新 style/TextAppearance.App.AllCaps