问题描述
我有一个普通的 EditText
字段,我想以编程方式更改其下划线颜色.
I have an ordinary EditText
field that I would like to programmatically change the underline color for.
<EditText
android:id="@+id/edit_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"/>
其他答案建议像这样更改背景颜色滤镜:
Other answers suggest changing the background color filter like so:
editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
但是,运行该应用程序时我看不到任何变化.更改背景本身:
However, I don't see any change when I run the app. Changing the background itself:
editText.setBackground(color)
将整个 EditText
更改为 color
-不是我想要的!
changes the entire EditText
to color
- not what I want!
如何以编程方式更改 EditText
, AppCompatEditText
或 TextInputEditText
的下划线颜色?我正在使用支持库的25.0.1版本.
How do I programmatically change the underline color for an EditText
, AppCompatEditText
or TextInputEditText
? I am using version 25.0.1 of the Support Library.
推荐答案
您需要在 EditText
backgroundTintList (或 supportBackgroundTintList
)>到 ColorStateList
的实例,该实例仅包含您希望将色调更改为的颜色.一种向后兼容的简单方法如下:
You need to set the backgroundTintList
(or supportBackgroundTintList
) on the EditText
to an instance of ColorStateList
containing only the color you wish to change the tint to. An easy way to do this in a backwards-compatible way looks like this:
ColorStateList colorStateList = ColorStateList.valueOf(color);
editText.setSupportBackgroundTintList(colorStateList);
这将为 EditText
提供所需的下划线颜色.
This will give the EditText
the desired underline color.
这篇关于以编程方式更改EditText的下划线颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!