开发者

Validating EditText content as soon as user enters data

开发者 https://www.devze.com 2023-01-12 12:27 出处:网络
I have 2 EditText widgets ,one takes username and other takes password.When the user enters username in First EditText ,the text should be validated (It should accept onl开发者_Go百科y characters no d

I have 2 EditText widgets ,one takes username and other takes password.When the user enters username in First EditText ,the text should be validated (It should accept onl开发者_Go百科y characters no digits) when the focus is on the first EditText. How to achieve this. It needs to display error message using setError() method in EditText when the user enters wrong data.


Here is your solution

user= (EditText) findViewById(R.id.editText_userName);
            user.addTextChangedListener(new TextWatcher(){

                @Override
                public void afterTextChanged(Editable arg0) {
                    if (!start.getText().toString().matches("[a-z]") || start.getText().toString() == null) {
                        start.setError("Letters Only");
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {}

                @Override
                public void onTextChanged(CharSequence arg0, int arg1,
                        int arg2, int arg3) {}

            });

implement same for password using your any match pattern of your choice. Hope it helps.


Attach a KeyListener to the EditText.

On an 'onKey' event, validate the field.

This will catch every character the user enters and validate it. When the EditText is changed, android clears the error thus the error message will not show if the entry is valid and if it is not valid, set the error (Username.setError("Error")) so that the error message while show/remain.

One warning, this works on one of my activities but when I implemented it on another activity, the EditText error doesn't get cleared when the user inputs data.

0

精彩评论

暂无评论...
验证码 换一张
取 消