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

标签 android

我有一个普通的 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)

将整个 EditText 更改为 color - 这不是我想要的!

如何以编程方式更改 EditTextAppCompatEditTextTextInputEditText 的下划线颜色?我使用的是支持库的 25.0.1 版。

最佳答案

@degs 的回答是正确的。但只需添加一个小注释:AppCompatEditText#setSupportBackgroundTintList 现在带有 @RestrictTo(LIBRARY_GROUP) 注释,这意味着:

Restrict usage to code within the same group of libraries

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

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

关于android - 以编程方式更改 EditText 的下划线颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40838069/

相关文章:

android - 为 Android Intents 定义接口(interface)

android - 更新以支持库 23.2.1 后,RecyclerView 项目底部有非常大的空白空间

android - 在 Android 上持久化数据的建议?

android - Android Studio 上的多设备 View ?

java - ArrayList <Word> 无法转换为 int

android - 如何在 Android 屏幕关闭时让 CPU 远离 'sleeping'?

android - 如何将 Android Studio 的设置位置指向不同的自定义位置?

java - 如何在 Android Realm 中保存对象列表?

android - 在 Android NDK 上使用 ffmpeg 淡入淡出图片

java - RecyclerAdapter getItemCount 崩溃