【发布时间】:2020-12-23 01:03:54
【问题描述】:
在使用 Kotlin 开发的 Android 应用程序中,有一个 EditText,它只接受被视为美元的数字。输入需要格式化为 2 位小数,因此输入需要格式化如下
- 7 -> 0.07
- 73 -> 0.73
- 736 -> 7.36
尝试使用输入过滤器。输入过滤器也用于限制最大值和单个十进制输入条目。
editTextField.filters =
arrayOf(DecimalInputFilter())
class DecimalDigitsInputFilter() : InputFilter {
override fun filter(
source: CharSequence?,
start: Int,
end: Int,
dest: Spanned?,
dstart: Int,
dend: Int
): CharSequence? {}
}
无法格式化数字。能够根据规则限制输入。
editTextField.addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
print("beforeTextChanged")
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
print("onTextChanged")
val inputFormatter = DecimalFormat("0.00")
inputFormatter.isDecimalSeparatorAlwaysShown = true
inputFormatter.minimumFractionDigits = 2
editTextField.setText((s.toString()).format(inputFormatter))
}
override fun afterTextChanged(s: Editable?) {
print("afterTextChanged")
}
})
这也失败了。
【问题讨论】:
-
deliveryTipValue和editTextField不同吗? -
用正确的名称更新了问题。谢谢
标签: android kotlin decimalformat android-textwatcher addtextchangedlistener