【发布时间】:2021-12-31 15:27:16
【问题描述】:
如何使 TextField 只接受整数作为输入,如何将小数点前的位数限制为 3,小数点后的位数限制为 2?
例如 NNN.NN,其中 N 是数字。
【问题讨论】:
标签: android-studio kotlin android-jetpack-compose
如何使 TextField 只接受整数作为输入,如何将小数点前的位数限制为 3,小数点后的位数限制为 2?
例如 NNN.NN,其中 N 是数字。
【问题讨论】:
标签: android-studio kotlin android-jetpack-compose
第一步是为 TextField 设置 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)。这将在 TextField 获得焦点时打开数字键盘。
现在的问题是 TextField 本身不进行任何验证(与带有 inputType="number" 的 EditText 不同)。用户可以键入键盘上存在的任何字符(如逗号、空格、破折号,甚至多个小数)。您需要自己完成所有这些验证。
试试这个代码:
var number by remember { mutableStateOf("") }
TextField(
value = number,
onValueChange = { number = getValidatedNumber(it) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
fun getValidatedNumber(text: String): String {
// Start by filtering out unwanted characters like commas and multiple decimals
val filteredChars = text.filterIndexed { index, c ->
c in "0123456789" || // Take all digits
(c == '.' && text.indexOf('.') == index) // Take only the first decimal
}
// Now we need to remove extra digits from the input
return if(filteredChars.contains('.')) {
val beforeDecimal = filteredChars.substringBefore('.')
val afterDecimal = filteredChars.substringAfter('.')
beforeDecimal.take(3) + "." + afterDecimal.take(2) // If decimal is present, take first 3 digits before decimal and first 2 digits after decimal
} else {
filteredChars.take(3) // If there is no decimal, just take the first 3 digits
}
}
我没有测试过这段代码,但我认为它应该适用于大多数情况。它将确保最终输入不会超过原始约束,但可能会导致一些意外行为。例如:
对于用户更改光标位置和输入内容的这些极端情况,您必须确定正确的行为应该是什么(就像在我的第一个示例中,您可能选择不允许删除小数并保留原始文本)。您必须根据您的确切要求在 getValidatedNumber 函数中添加此类条件。我有时在这里使用的一种解决方法是禁用光标位置更改,即光标将始终保留在末尾并且不能被带到任意索引。
【讨论】: