【问题标题】:TextInputLayout - setError Does Not Change Floating Hint Colour To Error ColourTextInputLayout - setError 不会将浮动提示颜色更改为错误颜色
【发布时间】:2018-06-14 12:34:30
【问题描述】:

我遇到了 TextInputLayout 错误状态的问题。当我在 TextInputLayout 上设置错误时,错误消息是红色的,还有下划线,但提示没有(它保持默认颜色 - 灰色)。我尝试过设置 errorTextAppearance,但似乎无法让提示文本更改颜色。

<android.support.design.widget.TextInputLayout
            android:id="@+id/textInputLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="My Hint"
            app:errorTextAppearance="@style/MyErrorTextAppearance">

<android.support.design.widget.TextInputEditText
                android:id="@+id/editText1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="number"
                android:maxLength="10"
                android:maxLines="1" />

styles.xml

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="MyErrorTextAppearance" parent="TextAppearance.Design.Error">
    <item name="android:textColor">@color/colorError</item>
</style>

我设置并清除错误如下:

myTextInputLayout.setErrorEnabled(true);
myTextInputLayout.setError(errorMessage);

myTextInputLayout.setError(null);
myTextInputLayout.setErrorEnabled(false);

【问题讨论】:

  • 我不能成为唯一的人吗?

标签: android android-styles android-textinputlayout android-textinputedittext


【解决方案1】:

试试下面的代码:

fun setHintColor(@ColorInt color: Int)
{
    try {
        var stateList = ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(color))
        val defaultTextColorField = TextInputLayout::class.java.getDeclaredField("mDefaultTextColor")
        defaultTextColorField?.let {field->
            field.isAccessible = true
            field.set(this, stateList)
        }
        val focusedTextColorField = TextInputLayout::class.java.getDeclaredField("mFocusedTextColor")
        focusedTextColorField?.let{field->
            field.isAccessible = true
            field.set(this, stateList)
        }
    }catch(e: java.lang.Exception){
        // handle exception
    }
}

【讨论】:

  • 你能稍微解释一下这段代码吗?它是如何回答问题的?
  • mDefaultTextColor 由 TextInputLayout 内部用于提示,而 mFocusedTextColor 用于标签。当您调用 setErrorTextAppearance 时,只有 mFocusedTextColor 会受到影响,这就是为什么您会看到标签更改为您的颜色,但只有当编辑字段具有焦点时。不幸的是,要更改提示颜色,您需要使用反射来访问 mDefaultTextColor。希望这会有所帮助。
猜你喜欢
  • 2020-06-05
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
相关资源
最近更新 更多