以编程方式更改EditText的下划线颜色

deg*_*egs 8 android

我有一个普通的EditText字段,我想以编程方式更改下划线颜色.

<EditText
    android:id="@+id/edit_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"/>
Run Code Online (Sandbox Code Playgroud)

其他答案建议更改背景颜色过滤器,如下所示:

editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
Run Code Online (Sandbox Code Playgroud)

但是,当我运行应用程序时,我没有看到任何变化.改变背景本身:

editText.setBackground(color)
Run Code Online (Sandbox Code Playgroud)

改变了整个EditTextcolor-不是我想要的!

如何编程方式更改下划线颜色的EditText,AppCompatEditText还是TextInputEditText?我使用的是支持库的25.0.1版.

Aar*_* He 23

@degs的答案是对的.但只需添加一个小注释:AppCompatEditText#setSupportBackgroundTintList现在注释用以下@RestrictTo(LIBRARY_GROUP)内容:

限制使用同一组库中的代码

而是使用ViewCompat#setBackgroundTintList.所以在你的例子中,它应该是这样的:

ColorStateList colorStateList = ColorStateList.valueOf(color);
ViewCompat.setBackgroundTintList(editText, colorStateList);
Run Code Online (Sandbox Code Playgroud)

  • 它可以工作,但当我点击编辑文本以使其获得焦点时,颜色将更改为accentColor.怎么处理这个.如果它改变了某些内容,我的edittext就在TextInputLayout内部.谢谢 (4认同)

deg*_*egs 20

您需要将backgroundTintList(或supportBackgroundTintList)设置为仅包含您要将颜色更改为的颜色EditText的实例ColorStateList.以向后兼容的方式执行此操作的简单方法如下所示:

ColorStateList colorStateList = ColorStateList.valueOf(color)
editText.setSupportBackgroundTintList(colorStateList)
Run Code Online (Sandbox Code Playgroud)

这将给出EditText所需的下划线颜色.

  • 仅供参考,要让 `setSupportBackgroundTintList` 工作(并在 API 19+ 中使用 `setBackgroundTintList`,您需要使用 `AppCompatEditText` 而不是 `EditText` (2认同)
  • 或者你可以使用`ColorStateList colorStateList = ColorStateList.valueOf(color)``ViewCompat.setBackgroundTintList(editText, colorStateList)` (2认同)