我试图将style
应用于EditText
来改变它的colorAccent
,我试图设置它的style
和android:textAppearance
,但它完全忽略了我的新设置。我让它工作的唯一方法是设置它的android:theme
。
我做错了什么或这是预期的行为?为什么?
我的风格:
<style name="bright_color_cursor" parent="AppTheme">
<item name="colorAccent">@color/primaryBrightColor</item>
<item name="android:textColorHighlight">@color/primaryBrightColor</item>
</style>
我的EditText
:
<EditText
android:id="@+id/edit_text"
android:theme="@style/bright_color_cursor"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:background="@android:color/transparent"
android:ems="10"
android:hint="@string/hello"
android:inputType="textCapWords"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/name_edit_text"
app:layout_constraintTop_toBottomOf="@+id/divider" />
将android:theme
更改为任何此设置将不起作用:
style="@style/bright_color_cursor"
要么
android:textAppearance="@style/bright_color_cursor"
是的,使用EditText可以预期这种行为。我们需要使用android:theme
属性来设置它的样式。
使用@style
时,EditText不使用我们设置的值(因此似乎忽略了样式)。这是因为EditText会创建一些未设置样式的子视图。请参阅下面的详细说明。
详细解释和原因
1)首先,尝试了选项的含义以及它们的作用:
style
:(注意:没有前缀android:
):这仅为组件本身设置样式,并且不会更改其底层子视图/布局的样式。android:theme
:这基本上适用于样式本身,并将样式应用于它的子视图/布局。android:textAppearance
:这个表现就像@style
造型一样。2)EditText
功能
我们可以想象:EditText不仅仅是一个简单的视图。它具有可绘制的背景并处理交互等。它只需要一些额外的视图(和逻辑)来使这个功能起作用。
对于EditText
的功能,它添加了一些子视图作为子项,以便能够做我们对它的期望。
3)回到主题
EditText
添加的子视图执行它的功能,其样式与其他视图的样式一样。这意味着当我们使用android:theme
属性时,子视图仅继承样式。因为此属性也会导致子视图的样式。
而且,如果我们在edittext上使用@style
,孩子们就不会得到这种风格。
4)为什么会(仅)为EditText发生这种情况?
嗯,不仅仅是...... EditText
的基本视图是TextView
,但TextView
不提供EditText
需要的功能。所以EditText
本身就增加了额外的功能。
例如,Button
也有TextView
作为基础。但是这个类有足够的视图,它有从基类获得的文本和背景,因此Button
不需要为它的功能添加额外的视图。所以对于这个,使用@style
工作,因为它创建没有儿童视图风格。
说了这么一句话:实际上,在源代码中,TextView
实际上包含了编辑逻辑,但是在Button
的情况下,它根本就不执行那部分代码。 (一个按钮不需要Editting
功能,因此它没有被执行)