验证仅允许android中编辑文本中的数字和字符

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

这是我的代码

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 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,应用程序是强制关闭.请给我建议.谢谢提前.

解决方法

而不是使用您的“手动”检查方法,在Android中有一些非常容易的东西:
InputFilter filter = new InputFilter() { 
    public CharSequence filter(CharSequence source,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});

或者另一种方法:在xml中设置允许的字符,您正在创建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"
/>

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...