【问题标题】:TextWatcher is preveting delete whole string from EditText, just char to charTextWatcher 阻止从 EditText 中删除整个字符串,只是从字符到字符
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 我不能,因为每一个变化,甚至是擦除一些东西,我都需要调整金钱面具
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2016-07-26
    • 2013-09-18
    • 2011-11-22
    相关资源
    最近更新 更多