TextWatcher正在从EditText中删除整个字符串,只是字符到字符



我有一个使用TextWatcher的Editext来制作货币掩码。

工作正常,但是当我尝试删除文本时,按住软键盘的退格键,除非我多次重复按键,否则文本不会被删除。

我认为这可能是因为每个文本都会更改,我必须调用 setText,这扰乱了流程。

有什么建议吗?

myEditText.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int,
before: Int, count: Int) {
}
override fun beforeTextChanged(s: CharSequence, start: Int,
count: Int, after: Int) {
}
override fun afterTextChanged(editable: Editable) {
myEditText.removeTextChangedListener(this)
val parsed = parseToBigDecimal(editable.toString(), locale)
val formatted = NumberFormat.getCurrencyInstance(locale).format(parsed)
myEditText.setText(formatted)
myEditText.setSelection(formatted.length)
myEditText.addTextChangedListener(this)
}
})

private fun parseToBigDecimal(value: String, locale: Locale): BigDecimal {
val replaceable = String.format("[%s,.\s]", NumberFormat.getCurrencyInstance(locale).currency.symbol)
val cleanString = value.replace(replaceable.toRegex(), "")
return BigDecimal(cleanString).setScale(
2, BigDecimal.ROUND_FLOOR).divide(BigDecimal(100), BigDecimal.ROUND_FLOOR
)
}

在其中一个方法中,您可以检测是否删除了文本。然后,您可以设置一个标志来跳过/处理/区分afterTextChanged中的任何内容。

override fun onTextChanged(s: CharSequence, start: Int,
before: Int, count: Int) {
}
override fun beforeTextChanged(s: CharSequence, start: Int,
count: Int, after: Int) {
}

最新更新