By default, when an error is set on a TextInputLayout, the hint textColor is changed to the error color. To prevent this behavior, you can use a custom style for the TextInputLayout that overrides the hint textColor and the error textColor. It's a step-by-step process, follow me:
First step:
Create a new style in your styles.xml file that extends the default Widget.MaterialComponents.TextInputLayout.FilledBox
style:
<style name="MyTextInputLayoutStyle" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
<item name="hintTextColor">@color/my_text_input_layout_hint_color</item>
<item name="errorTextColor">@color/my_text_input_layout_error_color</item>
</style>
Second step:
Apply the custom style to your TextInputLayout in the layout file. Here's an example:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/my_text_input_layout"
style="@style/MyTextInputLayoutStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="My Hint Text">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/my_text_input_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
Third step:
In your code, when you want to set an error on the TextInputLayout, use the setError()
function (and not .error
) like this:
myTextInputLayout.setError("My Error Message", false)
Note that the second parameter in the setError()
function is set to false
. This way, the TextInputLayout doesn't change the hint textColor when an error is set. Instead, the error text color will be used for the error message.