EditText设置只允许输入文字、拼音、数字
给EditText添加上监听,根据自己的需求,在相应的监听上写上相应的功能
tv_editText = findViewById(R.id.tv_editText); tv_editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { String edit = tv_editText.getText().toString(); String str = stringFilter(edit.toString()); if (!edit.equals(str)) { tv_editText.setText(str); //设置新的光标所在位置 tv_editText.setSelection(str.length()); } } @Override public void afterTextChanged(Editable editable) { } });
通过正则表达式来判断,设置只允许输入文字、拼音、数字
public static String stringFilter(String str) throws PatternSyntaxException { // 只允许字母、数字和汉字其余的还可以随时添加比如下划线什么的,但是注意引文符号和中文符号区别 String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";//正则表达式 Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); }