EditText限制輸入字元型別
阿新 • • 發佈:2018-12-15
最近有一個EditText內只能輸入數字,字母,漢字的字元型別限制,隨手整理一下,有新的內容以後在做修改
fun stringFilter(str: String): String {
val regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]"
val pattern = Pattern.compile(regEx)
val matcher = pattern.matcher(str)
return matcher.replaceAll("").trim()
}
device_name.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { name = stringFilter(s.toString()) if (s.toString() != name) { device_name.setText(name) device_name.setSelection(name.length) } } override fun afterTextChanged(s: Editable) {} })
禁止輸入表情
val emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);