Android EditText change focus after validation and

2019-07-09 07:16发布

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 setOnFocusChangeListener on there that will validate the input. If the validation fails a Dialog opens with a message and an OK button.

After the Dialog is closed I tried a requestFocus on my User EditText in many variations, by releasing it on Pass, by trying to release on User again, by requesting than clearing and requesting again but when I click on another field the softkeyboard won't open again or I end up with two EditText fields with the blinking cursor.

Any ideas?

1条回答
爷、活的狠高调
2楼-- · 2019-07-09 07:43

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

EditText textbox = new EditText(context);
textbox.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                // Your validation code goes here
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(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(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(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")).

查看更多
登录 后发表回答