我有一个Editext,它使用TextWatcher制作货币掩码。
工作正常,但是当我尝试删除文本时,按住软键盘上的退格键,则不会删除文本,除非我多次重复按该键。
我认为这可能是因为每个文本都发生了变化,我必须调用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
)
}
答案 0 :(得分:0)
在这些方法之一中,您可以检测是否删除了文本。然后,您可以设置标志以跳过/处理/区分afterTextChanged
中的内容。
override fun onTextChanged(s: CharSequence, start: Int,
before: Int, count: Int) {
}
override fun beforeTextChanged(s: CharSequence, start: Int,
count: Int, after: Int) {
}