kmn kmn - 19 days ago 6
Android Question

Design Android EditText to show error message as described by google

I need an

EditText
that looks like this onError:

enter image description here

calling onError looks like this instead :

enter image description here

Note: the app is running on SDK 19 (4.4.2)

min SDK is 1

Is there a method similar to setError that does this automatically,
or do I have to write the code for it ?

Thank you

Answer

There's no need to use a third-party library since Google introduced the TextInputLayout as part of the design-support-library.

Following a basic example:

Layout

<android.support.design.widget.TextInputLayout
    android:id="@+id/text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />
</android.support.design.widget.TextInputLayout>

Code

In order to show the Error below the EditText you simply need to call #setError on the TextInputLayout:

TextInputLayout til = (TextInputLayout) findViewById(R.id.text_input_layout);
til.setErrorEnabled(true);
til.setError("You need to enter a name");

Result

picture showing the edit text with the error message

Note

In order to use the TextInputLayout you have to add the following to your build.gradle dependencies:

dependencies {
    compile 'com.android.support:design:22.2.0'
}

Edit

In order to make the line of the EditText red as well, you can use the following code as soon as you call setError:

editText.getBackground().setColorFilter(getResources().getColor(R.color.red_500_primary), PorterDuff.Mode.SRC_ATOP);

Edit #2

saveman71 pointed out in the comments, that the code above isn't needed anymore. That's true, so the call to setError should be enough.

Comments