android中EditText只允许输入汉字(过滤汉字)
程序员文章站
2022-06-14 22:07:51
...
step1:Utils中添加过滤方法
object Utils {
/**
* 手机号验证
*
* @param str
* @return 验证通过返回true
*/
fun isMobile(str: String): Boolean {
val p = Pattern.compile("^1[0-9]{10}$") // 验证手机号
val m = p.matcher(str)
return m.matches()
}
/**
* 过滤汉字
*/
fun filterChinese(str: String): String {
val regEx = "[^\u4E00-\u9FA5]"
val p: Pattern = Pattern.compile(regEx)
val m = p.matcher(str)
return m.replaceAll("").trim()
}
}
2edittext的TextWatcher监听方法中使用
etName.addTextChangedListener(object : TextWatcher {
lateinit var s2: String
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val s1 = etName.text.toString().trim()
s2 = Utils.filterChinese(s1)
if (!TextUtils.equals(s1, s2)) {
etName.setText(s2)
etName.setSelection(s2.length)
}
}
})