1.手机号添加空格方式
binding.etContent.addTextChangedListener(object :TextWatcher {
override fun beforeTextChanged(
charSequence:CharSequence?,
before:Int,
count:Int,
p3:Int
) {
}
override fun onTextChanged(
charSequence:CharSequence?,
start:Int,
before:Int,
count:Int
) {
val length = charSequence?.length ?:0
Log.d(TAG,"onTextChanged: ==" + charSequence)
//基本上都是一个一个输入 count 是1
if (count ==1) {
/**
* 手机号为 11位 格式化为 181 2101 0518 需要加 俩空格 可以设置 maxLength 为11+2
* 在判断输入到第几位时加入空格
*/
if (length ==4 ||length ==9) {
val sb = StringBuffer(charSequence)
sb.insert(length -1,"\u2000")
binding.etContent.setText(sb)
// 设置光标
binding.etContent.setSelection(
binding.etContent.getText().toString().length
)
}
}else if (before ==1) {
// 删除的时候需要把空格删除掉
val str = charSequence.toString().trim()
binding.etContent.setText(str)
// 设置光标
binding.etContent.setSelection(
binding.etContent.getText().toString().length
)
}
}
override fun afterTextChanged(p0:Editable?) {
}
})
2. 身份证号码添加空格
```
binding.etContent.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(
charSequence: CharSequence?,
before: Int,
count: Int,
p3: Int
) {
}
override fun onTextChanged(
charSequence: CharSequence?,
start: Int,
before: Int,
count: Int
) {
val length = charSequence?.length ?: 0
//基本上都是一个一个输入 count 是 1
if (count == 1) {
if (length == 5 || length == 10 || length == 15 || length == 20) {
val sb = StringBuffer(charSequence)
sb.insert(length - 1, "\u2000")
binding.etContent.setText(sb)
// 设置光标
binding.etContent.setSelection(
binding.etContent.getText().toString().length
)
}
} else if (before == 1) {
// 删除的时候需要把空格删除掉
val str = charSequence.toString().trim()
binding.etContent.setText(str)
// 设置光标
binding.etContent.setSelection(
binding.etContent.getText().toString().length
)
}
}
override fun afterTextChanged(p0: Editable?) {
}
})
```