Xc0d3r
Xc0d3r

Reputation: 581

setError alongwith onClick for EditText

Normal error displayed using setError() method:

Screenshot #1

Problem:

Screenshot #2

Okay so I have another EditText in same dialog having an OnClickListener for showing the DatePicker dialog. When I setError() it shows the red alert icon and when I click on that icon, the event is still handled by OnClick on EditText and DatePicker pops up, hence I cannot view the error message.

What I want : If I click on the icon, it must show the error message, and if I click outside the icon it should show the DatePicker.

Upvotes: 5

Views: 2237

Answers (4)

Vucko
Vucko

Reputation: 7479

Oh man, I literally had this problem 2 days ago. I found no way to make it both HAVE focus (in order to display the message, AND also create a pop-up of the date picker. What I ended up doing is wrapping EditText into a TextInputLayout like this:

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

            <EditText
                android:id="@+id/input_birth_date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/birth_date_hint"
                android:inputType="date" />
        </android.support.design.widget.TextInputLayout>

And then instead of setting the error on the edit text, I set the error on the TextInputLayout instead like this:

birthDateInputLayout.setErrorEnabled(true);
birthDateInputLayout.setError("This field cannot be empty.");

NOTE: It does not look exactly the same as the regular way of setting error on EditText, but it does look nice enough and solves the problem a bit differently.

Here's a screenshot of how it looks: enter image description here

Upvotes: 2

Quick learner
Quick learner

Reputation: 11477

Try this ,

onClick(View v){
    if(editText.getError() != null ){
       editText.requestFocus(); // to show error message
    }else{
        // open date picker dialog here or do you stuff here 
    }

hope it helps

Upvotes: 0

Vishal kumar singhvi
Vishal kumar singhvi

Reputation: 966

you can use this following code according to your code when complete all field and second date edit text set error to null.any query you can ask

mEditText.setError(null);//removes error
mEditText.clearFocus();    //clear focus from edit text

Upvotes: 0

Febi M Felix
Febi M Felix

Reputation: 2849

A simple solution is to check whether error is null inside onclickListener. ie,

if(((EditText)view).getError() == null) {
//Handle your click for showing picker
}

Upvotes: 0

Related Questions