android - 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
任何时候的价值fuelAmount
或fuelCost
改变。
解决方案
TextView.setText(..)
将一次又一次地触发 TextWatcher,这就是循环发生的方式。
做例如(伪代码)之类的事情,
val cost = fuelCost / fuelAmount
if (fuelPricePerUnit.text != cost)
fuelPricePerUnit.setText(cost)
很可能会让你摆脱困境。
让我知道我是否可以提供进一步的帮助。
推荐阅读
- node.js - 如何在续集中循环结果
- ruby-on-rails - rails 5 webpack 4 处理 css 文件
- python - AttributeError: 'super' object has no attribute '__getattr__' 在 Kivy 中使用带有多个 kv 文件的 BoxLayout 时出错
- groovy - 传递 Map 和使用 `body.resolveStrategy = Closure.DELEGATE_FIRST` 有什么区别
- angular - Angular 7 将路由器从 AppModule 传递到自定义库
- google-apps-script - pageElement 上的调用方法失败并出现错误“TypeError:找不到函数”
- intellij-idea - 如何将我的 IntelliJ IDEA 插件重置为默认值?
- java - 试图理解 RxJavaFX 的重点
- python - 如何在 for 循环中修改 Numpy 数组
- shell - 使用 shell 脚本将多个 csv 文件附加到单个 csv 文件中