【问题标题】:Why EditText only accepts Theme?为什么 EditText 只接受主题?
【发布时间】:2018-09-06 21:52:00
【问题描述】:

我试图将style 应用到EditText 以更改它的colorAccent,我尝试设置它的styleandroid: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"

【问题讨论】:

  • "我做错了什么" 如果您发布您的代码/xml,我们或许可以告诉...
  • 大声笑,我这很容易复制,我的代码就像我在帖子中所说的那样简单,但是你想要它,好的。
  • 好的,我刚刚放了我的代码,正如我所说,它非常简单......现在人们对它投了这么多,我怀疑我会从中得到任何答案:/
  • 对于android:style,该值需要是扩展 TextAppearance 的样式资源:developer.android.com/guide/topics/ui/look-and-feel/themesandroid:textAppearance 需要一个属性:stackoverflow.com/questions/24237616/…
  • 不就是style吗?

标签: android android-edittext android-theme android-styles


【解决方案1】:

是的,EditText 会出现这种行为。我们需要使用android:theme 属性对其进行样式设置。

当使用@style 时,EditText 不使用我们设置的值(因此样式似乎 被忽略了)。这是因为 EditText 创建了一些未设置样式的子视图。请参阅下面的详细说明。


详细解释及原因

1)首先,尝试的选项的含义以及它们的作用:

  • style:(注意:不以 android: 为前缀):这为组件本身设置样式,并且更改其底层子视图的样式/布局。
  • android:theme:这基本上适用于自身的样式并且将样式应用于它的视图/布局。
  • android:textAppearance:这个在样式方面的行为就像 @style

2) EditText 功能

我们可以想象:一个 EditText 不仅仅是一个简单的视图。它有一个可绘制的背景并处理交互等。它只需要一些额外的视图(和逻辑)才能使此功能正常工作。

对于EditText 的功能,它添加 一些子视图作为子视图,以便能够执行我们期望的操作。

3) 回到主题

EditText 添加的子视图用于实现其功能,其样式与其他视图的样式相同。这意味着子视图只有在我们使用android:theme 属性时才会继承样式。因为这个属性会导致它也为子视图设置样式。

而且,如果我们在编辑文本上使用@style,孩子不会获得这种风格。

4) 为什么(仅)EditText 会发生这种情况?

嗯,不是真的只是...EditText 的基本视图是TextView,但TextView 不提供EditText 所需的功能。所以EditText 本身增加了额外的功能。

例如Button 也有TextView 作为基础。但是这个类有足够的视图和从基类获得的文本和背景,因此Button 不需要为它的功能添加额外的视图。因此,为此,使用 @style 可以正常工作,因为它不会创建子视图来设置样式。

说了这么多,顺便说一句: 事实上,在源代码中,TextView 实际上包含编辑逻辑,但在Button 的情况下,它根本不执行那部分代码。 (按钮不需要Editting 功能,因此它不会被执行)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2012-03-09
    • 2013-12-01
    • 1970-01-01
    相关资源
    最近更新 更多