android - 输入掩码(红色疯狂机器人)自动删除空格
问题描述
我想以[0000] [0000] [0000] [0000]等格式为edittext创建信用卡掩码掩码,但用户不应该手动删除空格
例如:
“4444_4444_4”
“444_4444_”
如何实现自动删除空格“”?
解决方案
Try this. Hope it will help. (Kotlin example)
class CreditCardFormattingTextWatcher : TextWatcher {
private var etCard: EditText? = null
private var isDelete: Boolean = false
constructor(etcard: EditText) {
this.etCard = etcard
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
isDelete = before != 0
}
override fun afterTextChanged(s: Editable) {
val source = s.toString()
val length = source.length
val stringBuilder = StringBuilder()
stringBuilder.append(source)
if (length > 0 && length % 5 == 0) {
if (isDelete)
stringBuilder.deleteCharAt(length - 1)
else
stringBuilder.insert(length - 1, " ")
etCard?.setText(stringBuilder)
etCard?.setSelection(etCard?.text?.length ?: 0)
}
}
}
推荐阅读
- batch-file - 如何在限制范围内生成随机数?
- javascript - 删除特殊字符 Javascript
- r - 如何将时间添加到 netcdf 文件?
- mysql - 这个版本的 MariaDB 还不支持 'LIMIT & IN/ALL/ANY/SOME 子查询' - Multiple WHEREs and LIMITS
- python - 无法使用 igraph 函数“all_simple_paths”
- java - .NET 中的不可变列表:为什么允许添加和删除项目?
- python - 在python中绘制数字列表
- python - 如何根据列值使用 plotly 分配颜色值?
- flutter - 无法运行 Flutter_blue、BLE 插件的示例应用
- mysql - 无法卸载 mysql 损坏的 mysql / 安装新的 mysql