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

15

我有一个普通的EditText字段,我希望在程序中可以更改下划线的颜色。

<EditText
    android:id="@+id/edit_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"/>

其他答案建议像这样更改背景颜色过滤器:

editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);

然而,当我运行应用程序时,我没有看到任何变化。仅仅改变了背景本身:

editText.setBackground(color)

如何以编程方式更改EditTextAppCompatEditTextTextInputEditText的下划线颜色?我正在使用Support Library的25.0.1版本。

EditText整体变为color-这不是我想要的!

4个回答

38

@degs的回答是正确的。但是需要补充一点注释:AppCompatEditText#setSupportBackgroundTintList现在已经用 @RestrictTo(LIBRARY_GROUP)进行了注释,这意味着:

  

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

请改用ViewCompat#setBackgroundTintList。因此,在您的示例中,应该像这样:

ColorStateList colorStateList = ColorStateList.valueOf(color);
ViewCompat.setBackgroundTintList(editText, colorStateList);

5
可以。当我点击EditText让它获得焦点时,颜色会改变为accentColor,虽然程序可以正常运行,但该如何解决这个问题呢?如果TextInputLayout对此有影响,请一并考虑,谢谢。 - JerabekJakub
1
@JerabekJakub 将 onFocusChangeListener 附加到您的 editText,然后重写它。 - sissyphus_69
1
@godslayer_69 感谢你的提示,我已经添加了监听器,但是不知道在 onFocusChange(View view, boolean b) {...} 方法中应该添加什么。我尝试了与答案相同的方法,但没有任何积极的效果。你能否请更具体一些?public void onFocusChange(View view, boolean b) { ColorStateList colorStateList = ColorStateList.valueOf(Color.parseColor("#ff6600")); ViewCompat.setBackgroundTintList(editUsername, colorStateList); } - JerabekJakub
1
在onFocusChange中,从view中可以获取视图的id,布尔值b表示该视图是否处于焦点状态,true表示处于焦点状态,false表示未处于焦点状态。现在使用switch case,您可以选择为哪个视图发生什么情况,然后只需在需要时使用上述代码应用色调即可。例如:如果视图处于焦点状态,请使用色调执行某些操作;否则,请使用色调执行其他操作。 - sissyphus_69

26
您需要将 EditText 上的 backgroundTintList(或 supportBackgroundTintList)设置为仅包含您希望更改色调的颜色的ColorStateList实例。以向后兼容的方式轻松完成此操作的方法如下:
ColorStateList colorStateList = ColorStateList.valueOf(color);
editText.setSupportBackgroundTintList(colorStateList);

这将使EditText拥有所需的下划线颜色。


3
要使 setSupportBackgroundTintList 生效(并在 API 19+ 中使用 setBackgroundTintList),需要使用 AppCompatEditText 而不是 EditText - ElliotM
2
或者你可以使用以下代码:ColorStateList colorStateList = ColorStateList.valueOf(color); ViewCompat.setBackgroundTintList(editText, colorStateList); - John Codeos

0

通过使用ColorFilter类和其他方式,可以以编程方式更改EditText下划线的颜色,但您可能会遇到API级别问题。解决这些类型问题的最佳方法是使用9-Patch图像。

https://romannurik.github.io/AndroidAssetStudio/nine-patches.html前往此处下载一组可绘制对象并将它们放入drawable文件夹中,然后以编程方式更改EditText的背景(et_joker.setBackground(your_drawable);)这将在不考虑API级别的情况下工作。


0

当编辑文本处于焦点状态时,我无法使用上述解决方案使其正常工作。

我不得不在主题中添加colorControlActivated

<style name="StyledTilEditTextTheme">
   <item name="colorControlNormal">@color/greyLight</item>
   <item name="colorControlActivated">@color/gray_ccc</item>
</style>

这对我起作用了


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接