android使用正则表达式控制EditText只能输入数字和英文

在方法中加载

edt.addTextChangedListener(new SearchWather(edt));
新建类 SearchWather.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class SearchWather implements TextWatcher {

	private EditText pedt;
	
	public SearchWather(EditText edt){
		this.pedt=edt;
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		String editable = pedt.getText().toString();    
        String str = stringFilter(editable.toString());  
        if(!editable.equals(str)){  
        	pedt.setText(str);      
        	pedt.setSelection(str.length());  
        }
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		
	}
	
	public static String stringFilter(String str)throws PatternSyntaxException{       
	    // 只允许字母和数字         
	    String   regEx  =  "[^a-zA-Z0-9]";                       
	    Pattern   p   =   Pattern.compile(regEx);       
	    Matcher   m   =   p.matcher(str);       
	    return   m.replaceAll("").trim();       
	}

}

android使用正则表达式控制EditText只能输入数字和英文_第1张图片


你可能感兴趣的:(adnroid)