TextView的style和android:textAppearance属性有什么区别?

49

如果我将我的TextView定义为:

 <TextView
        style="@android:style/TextAppearance.DeviceDefault.Large"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

它基本上与执行以下操作相同:

 <TextView
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

我知道style是一种更广泛的限定符(即不能在android:textAppearance中设置所有属性),但这就引出了一个问题:为什么要费心呢?使用android:textAppearance是否有优势,而不是使用style

4个回答

13

从样式和主题中https://developer.android.com/guide/topics/ui/look-and-feel/themes#textappearance

样式的一个限制是您只能将一个样式应用于一个视图。但是,在TextView中,您还可以指定TextAppearance属性,该属性类似于样式。

TextAppearance允许您定义特定于文本的样式,同时保留View的样式供其他用途使用。但是,请注意,如果您直接在View或样式中定义任何文本属性,则这些值将覆盖TextAppearance值。


7

5

每个视图只能有一个样式属性,但使用TextAppearance允许您本质上使用受限的文本相关属性定义样式。您可以在一个视图中同时使用样式和TextAppearance。


5
您可以将样式与 TextAppearance 结合使用。
例如,在 TextAppearance 中,您可以为按钮设置所有与文本相关的逻辑。
在样式中,您可以重复使用它并添加额外的属性,例如填充、大小等。
例如,
<style name="TextAppearanceTitle" parent="TextAppearance.MaterialComponents.Button">
    <item name="android:textColor">#f0f</item>
</style>

<style name="SomeButtonStyle" parent="Widget.MaterialComponents.Button.UnelevatedButton">
    <item name="android:textAppearance">@style/TextAppearanceTitle</item>
    <item name="android:padding">12dp</item>
    <item name="android:elevation">4dp</item>
</style>

以下是TextView的TextAppearance所支持的属性列表,希望对您有所帮助:

<attr name="textColor" />
<attr name="textSize" />
<attr name="textStyle" />
<attr name="typeface" />
<attr name="fontFamily" />
<attr name="textColorHighlight" />
<attr name="textColorHint" />
<attr name="textColorLink" />
<attr name="textAllCaps" format="boolean" />
<attr name="shadowColor" format="color" />
<attr name="shadowDx" format="float" />
<attr name="shadowDy" format="float" />
<attr name="shadowRadius" format="float" />
<attr name="elegantTextHeight" format="boolean" />
<attr name="letterSpacing" format="float" />
<attr name="fontFeatureSettings" format="string" />

在样式中设置其余的内容。


为什么自动调整大小不是TextAppearance的一部分?它应该与文本相关。 - htafoya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接