Android EditText change focus after validation and showing the error in a Dialog

谁说胖子不能爱 提交于 2019-12-24 00:39:05

问题


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:


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")).



来源:https://stackoverflow.com/questions/5137933/android-edittext-change-focus-after-validation-and-showing-the-error-in-a-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!