etPhone.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) {
//手机号格式化xxx xxxx xxxx
if (s == null || s.isEmpty()) return
val sb = StringBuilder()
for (i in s.indices) {
if (i != 3 && i != 8 && s[i] == ' ') {
continue
} else {
sb.append(s[i])
if ((sb.length == 4 || sb.length == 9) && sb[sb.length - 1] != ' ') {
sb.insert(sb.length - 1, ' ')
}
}
}
if (sb.toString().trim().length != s.toString().length) {
var index = start + 1
if (sb.length>start){
if (sb[start] == ' ') {
if (before == 0) {
index++
} else {
index--
}
} else {
if (before == 1) {
index--
}
}
}else{
if (sb[sb.length-1] == ' ') {
index=sb.length-1
} else {
if (before == 1) {
index--
}
}
}
etPhone.setText(sb.toString().trim())
etPhone.setSelection(index)
}
}
override fun afterTextChanged(s: Editable?) {
if (s?.toString()?.replace(" ".toRegex(), "")?.length ?: 0 >= 11) {
etPassword.requestFocus()
}
}
})
04-05
622
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-04