【发布时间】:2019-03-13 13:37:35
【问题描述】:
我有一个使用 TextWatcher 的 Edittext 来制作货币掩码。
工作正常,但是当我尝试删除文本时,按住软键盘上的退格键,文本不会被删除,除非我多次重复按下该键。
我认为这可能是因为每个文本都发生了变化,我必须调用 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
)
}
【问题讨论】:
标签: android kotlin android-edittext masking textwatcher