【问题标题】:Setting error state in EditText through styles通过样式在 EditText 中设置错误状态
【发布时间】:2023-04-01 16:30:02
【问题描述】:

我有一个具有以下样式的 Edittext

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/white" android:state_focused="true" />
    <item android:color="@color/yellow" android:state_focused="false" />
    <item android:color="@color/white" android:state_active="true" />
</selector>

并且在我应用的 Edittext 样式中

<item name="backgroundTint">@drawable/states_edit_text</item>

它有效。这会更改正常状态和焦点状态下的 EditTexts 底线颜色。当它处于错误状态时,我需要将色调颜色更改为红色。

有点像

<item android:state_error="true" android:color="@color/red"></item>

但是没有称为错误的状态,我参考了其他答案,他们建议通过代码来实现。有什么方法可以使用 android 样式,我可以在错误状态下将 EditText 色调设置为红色?

【问题讨论】:

  • 您可以使用自己的状态制作自定义 EditText。 Here is an detail example.
  • 为什么不使用本身有错误状态和颜色的TextInputLayout和EditText呢?
  • @EhsanMashhadi 我知道 TextinputLayout 的解决方案,但这是一个已经存在的代码,其中许多 EditTexts 存在于多个屏幕中。我们需要在每个 EditText 中进行此更改。由于所有这些 EditText 都具有相同的样式,因此我尝试了一些仅使用样式的解决方案。

标签: android android-edittext


【解决方案1】:

我认为您可以通过编程方式更改它:

if (!trueState){

ColorStateList colorStateList = ColorStateList.valueOf(color)
editText.setSupportBackgroundTintList(colorStateList)

}  

这将为 EditText 提供所需的下划线颜色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2016-12-09
    • 2020-12-30
    相关资源
    最近更新 更多