首页 > 解决方案 > TextWatcher onTextChanged Android Kotlin 导致无限循环

问题描述

我有 3 个字段:fuelAmount、fuelPricePerUnit 和fuelCost。我想为每个字段添加一个 TextWatcher。
逻辑应该是这样的:
fuelCost = fuelAmount* fuelPricePerUnit
fuelPricePerUnit= fuelCost/fuelAmount

val refuelTextWatcher = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        override fun afterTextChanged(s: Editable?) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            if (fuelAmount.text.toString().isNotEmpty() && fuelAmount.text.toString().toFloat() > 0 && fuelPricePerUnit.text.toString().isNotEmpty()
            ) {
                val finalCost =
                    fuelAmount.text.toString().toFloat() * fuelPricePerUnit.text.toString()
                        .toFloat()

                fuelCost.setText(finalCost.toString())
            }
            else {
                /*Toast.makeText(
                    activity,
                    "Error!   ",
                    Toast.LENGTH_SHORT
                ).show()*/
            }
        }
    }
    fuelAmount.addTextChangedListener(refuelTextWatcher)
    fuelPricePerUnit.addTextChangedListener(refuelTextWatcher)

它只适用于 field fuelCost。我不知道如何让逻辑去做fuelPricePerUnit= fuelCost/fuelAmount因为我最终得到了无限循环或 NumberFormatException。
我也想改变fuelPricePerUnit任何时候的价值fuelAmountfuelCost改变。

标签: androidkotlin

解决方案


TextView.setText(..)将一次又一次地触发 TextWatcher,这就是循环发生的方式。

做例如(伪代码)之类的事情,

val cost = fuelCost / fuelAmount
if (fuelPricePerUnit.text != cost)
    fuelPricePerUnit.setText(cost)

很可能会让你摆脱困境。

让我知道我是否可以提供进一步的帮助。


推荐阅读