验证允许在Android的编辑文本只数和人物文本、编辑、人物、Android

2023-09-04 04:16:38 作者:原谅莪对迩旳伪冷漠-

在我的应用程序必须验证的EditText。它应该只允许字符,数字,下划线和连字符。

In my application i have to validate the edittext. It should only allow character, digits, underscore and hypen.

下面是我的code:

edittext.addTextChangedListener(new TextWatcher() {

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            // TODO Auto-generated method stub

                            }

                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                                            // TODO Auto-generated method stub

                            }

                                        @Override
                            public void afterTextChanged(Editable s) {
                                            // validation codes here

                            location_name=s.toString();
                            Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();                

                            if (location_name.matches(".*[^a-z^0-9].*")) 
                                {
                            location_name = location_name.replaceAll("[^a-z^0-9]", "");
                            s.append(location_name);
                            s.clear();
                            Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();

                            }

                            }

                        });     

location.add(location_name);

在此,当我进入输入的EditText,应用力closed.please给我suggestion.Thanks提前。

in this , when i entered input in edittext ,application is force closed.please give me suggestion.Thanks in advance.

推荐答案

而不是使用人工核对的方法,也有一些是非常简单的机器人:

Instead of using your "manual" checking method, there is something very easy in android:

InputFilter filter = new InputFilter() { 
    public CharSequence filter(CharSequence source, int start, int end, 
Spanned dest, int dstart, int dend) { 
            for (int i = start; i < end; i++) { 
                    if ( !Character.isLetterOrDigit(source.charAt(i)) || !Character.toString(source.charAt(i)) .equals("_") || !Character.toString(source.charAt(i)) .equals("-")) { 
                            return ""; 
                    } 
            } 
            return null; 
    } 
}; 

edit.setFilters(new InputFilter[]{filter}); 

或者另一种方法:设置允许的字符在您创建侑EDITTEXT的XML:

Or another approach: Set the allowed characters in the xml where you are creating yor EditTExt:

<EditText 
  android:inputType="text" 
  android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-" 
  android:hint="Only letters, digits, _ and - allowed"
/>