Skip to content Skip to sidebar Skip to footer

Android Edittext Change Focus After Validation And Showing The Error In A Dialog

I have a simple Activity with 3 EditText fields. User, Pass, Confirmation After typing something in the User field and the person clicks next on the keyboard, I have a setOnFocusCh

Solution 1:

I suggest validating the user's input with a TextWatcher:

EditTexttextbox=newEditText(context);
textbox.addTextChangedListener(newTextWatcher() {
            @OverridepublicvoidafterTextChanged(Editable s) {
                // Your validation code goes here
            }

            @OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {
            }

            @OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
            }
        });

Only handle validation in the afterTextChanged method, don't touch the other two, as advised in the documentation. However afterTextChanged get's fired, every time the input changes, so if the user enters the word "hello" this method get's called when h is entered, then again when e is entered and so on... Furthermore, if you modify the edittext value in afterTextChanged, the method get's called too.

An alternative is to validate the user input when the EditText loses focus. For this purpose you could use:

    textbox.setOnFocusChangeListener(newOnFocusChangeListener() {

        @OverridepublicvoidonFocusChange(View v, boolean hasFocus) {
            // Your validation code goes here
        }
    });

However beware, that some widgets might not grab focus, so your Edittext never loses it (had that with Buttons for instance).

Furthermore the EditText offers a setError method, which marks the edittext with a red error mark and shows the text passed to setError to the user (the text can be set by you when calling setError("Your error message")).

Post a Comment for "Android Edittext Change Focus After Validation And Showing The Error In A Dialog"