kotlin:
fun setEditTextFilter(editText: EditText){
val filterOne = InputFilter { source, start, end, dest, dstart, dend ->
if (source==" ") {
""
} else{
null
}
}//不能输入空格
val filterTwo = InputFilter { source, start, end, dest, dstart, dend ->
val pattern = Pattern.compile("[a-zA-Z|\u4e00-\u9fa5]+")
val matcher = pattern.matcher(source.toString())
if (!matcher.matches()){
""
}else{
null
}
}//只能输入中英文
editText.filters = arrayOf(filterOne,filterTwo)
}
java:
public static void setEditTextFilter(EditText editText){
InputFilter filterOne = new InputFilter(){
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.equals(" ")){
return "";
}else {
return null;
}
}
};//不能输入空格
InputFilter filterTwo = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Pattern pattern = Pattern.compile("[a-zA-Z|\u4e00-\u9fa5]+");
Matcher matcher = pattern.matcher(source);
if (!matcher.matches()) {
return "";
}else {
return null;
}
}
};//只能输入中英文
editText.setFilters(new InputFilter[]{filterOne,filterTwo});
}