How to fix background red color TextInputLayout when isEmpty in Android

user6761472 picture user6761472 · Aug 28, 2016 · Viewed 8.9k times · Source

I want setError when TextInputLayout isEmpty, I write this code but when show error message, set red background for TextInputLayout!

I do not want set background! I want just show the error message.

enter image description here

My code:

if (TextUtils.isEmpty(userName)) {
register_UserName_layout.setError("Insert Username");
}

XML code :

<android.support.design.widget.TextInputLayout
    android:id="@+id/register_userUsernameTextLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/register_headerLayout"
    android:layout_margin="10dp"
    android:textColorHint="#c5c5c5">

    <EditText
        android:id="@+id/register_userUserNameText"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@drawable/selector_bg_edit"
        android:hint="نام کاربری"
        android:paddingBottom="2dp"
        android:textColor="@color/colorAccent"
        android:textCursorDrawable="@drawable/bg_input_cursor"
        android:textSize="16sp" />
</android.support.design.widget.TextInputLayout>

How can I fix this? Thanks all <3

Answer

user7010102 picture user7010102 · Dec 12, 2016

I have found a workaround to this problem. You just need to create a custom EditText and override the getBackground() method of it to return a new drawable. That way TextInputLayout won't be able to set color filter on the EditText's background, since you do not return EditText's background, but some another drawable. See below:

@Override
public Drawable getBackground() {
    return ContextCompat.getDrawable(getContext(), R.drawable.some_drawable);
}

and use the custom EditText inside TextInputLayout:

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

        <CustomEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/custom_edit_text_bg" />

</android.support.design.widget.TextInputLayout>