如何修改TextInputLayout错误状态下的hint提示文字颜色
解决方案
你可以通过自定义样式+颜色选择器的方式实现需求,步骤如下:
- 第一步:在
res/color目录下创建hint_text_color.xml颜色选择器(如果没有color目录先手动新建)
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 错误状态下的hint颜色设置为红色 --> <item android:color="@android:color/holo_red_dark" android:state_enabled="true" android:state_error="true" /> <!-- 普通状态下的hint颜色,可自行调整 --> <item android:color="@android:color/darker_gray" android:state_enabled="true" /> <item android:color="@android:color/darker_gray" /> </selector>
- 第二步:在
res/values/styles.xml中自定义TextInputLayout的样式
<style name="CustomTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.FilledBox"> <item name="hintTextColor">@color/hint_text_color</item> <!-- 可同步设置错误提示文字、错误状态下的下划线颜色,避免视觉违和 --> <item name="errorTextColor">@android:color/holo_red_dark</item> <item name="boxStrokeErrorColor">@android:color/holo_red_dark</item> </style>
- 第三步:将样式应用到你的TextInputLayout控件上
修改原有布局代码,新增style属性:
<com.google.android.material.textfield.TextInputLayout android:id="@+id/editText5" style="@style/CustomTextInputLayoutStyle" android:layout_width="match_parent" android:layout_height="wrap_content" app:boxStrokeWidth="0dp" app:errorEnabled="true"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/password_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Login*" android:textSize="16sp" /> </com.google.android.material.textfield.TextInputLayout>
如果需要动态修改,也可以直接在代码中设置:
- Kotlin示例:
// 触发错误逻辑时调用 editText5.setHintTextColor(ContextCompat.getColorStateList(this, R.color.hint_text_color)) editText5.error = "输入错误"
- Java示例:
// 触发错误逻辑时调用 editText5.setHintTextColor(ContextCompat.getColorStateList(this, R.color.hint_text_color)); editText5.setError("输入错误");
注意事项
- 不要直接给TextInputEditText设置hint颜色,TextInputLayout的hint优先级更高,给子控件设置不会生效
- 确保Material组件库版本在1.1.0以上,低版本部分属性不支持
内容的提问来源于stack exchange,提问作者92sandeor
相关产品推荐
相关产品推荐

