android - 如何在 Kotlin 中禁止 Android EditText 中的“00”或“0123-like”输入开始?
问题描述
我有一个带有 numberDecimal 输入类型的 EditText 对象。输入操作(例如,计算)工作正常,但当前允许输入以“00”和“0123-like”(零后跟数字,而不是点)开头。
在 Kotlin 中,如何禁止以“00”或“0123-like”(零后跟数字,而不是点)开头的输入?
在谷歌搜索并阅读了许多类似的问题和答案后,我尝试了 TextWatcher 和 InputFilter,但无法真正找到解决方案。
解决方案
如果修改后的字符串格式为 0,则可以使用TextWatcher
正则表达式,后跟一个数字,可以删除最后插入的数字并返回仅包含初始 0 的字符串。
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val newText = s.toString().trim()
// Check if the text is 0 followed by another digit, in that case remove the last inserted value
if (newText.length > 1 && newText.matches("^0[\\d]+".toRegex())) {
// Unwanted expression: remove last inserted char and reset the cursor position to show after the first character
editText.setText("0")
editText.setSelection(1)
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
编辑
如果您需要将相同TextWatcher
应用于多个EditText
,您可以定义您的CustomTextWatcher
类:
class CustomTextWatcher(
private val editText: EditText
) : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
val newText = s.toString().trim()
// Check if the text is 0 followed by another digit, in that case remove the last inserted value
if (newText.length > 1 && newText.matches("^0[\\d]+".toRegex())) {
// Unwanted expression: remove last inserted char and reset the cursor position to show after the first character
editText.setText("0")
editText.setSelection(1)
}
}
}
然后将其添加到您EditText
的 s 中:
editText1.addTextChangedListener(CustomTextWatcher(editText1));
editText2.addTextChangedListener(CustomTextWatcher(editText2));
...