如何使TextField只接受整数作为输入,如何将十进制之前的数字数限制为3,小数点之后的数字数限制为2?
例如,NNN.NN,其中N是数字。
发布于 2021-11-22 03:40:17
第一步是为keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)设置TextField。当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
}
}我还没有测试过这段代码,但我认为它应该适用于大多数情况。它将确保最终输入不会超过原始约束,但它可能会导致一些意想不到的行为。例如:
如果当前文本为"123.45“,则为
对于用户更改光标位置和类型的这些角落情况,您必须决定正确的行为应该是什么(如我的第一个示例所示,您可能选择不允许十进制删除并保留原始文本)。您必须根据您的确切需求在getValidatedNumber函数中添加这样的条件。我有时在这里使用的一个解决方法是禁用游标位置更改,即游标始终保持在末尾,不能被带到任意的索引中。
发布于 2022-09-14 12:08:28
由于@Arpit编写了一个很好的函数,我在开始使用.输入时遇到了问题,为了使函数不允许.作为第一个字符,我对函数进行了如下更新:
private fun getValidatedNumber(text: String): String {
val filteredChars = text.filterIndexed { index, c ->
c.isDigit()
|| (c == '.' && index != 0 && text.indexOf('.') == index)
|| (c == '.' && index != 0 && text.count{ it == '.'} <=1)
}
// If dot is present, take first 3 digits before decimal and first 2 digits after decimal
return if (filteredChars.count{it == '.'} == 1 ) {
val beforeDecimal = filteredChars.substringBefore('.')
val afterDecimal = filteredChars.substringAfter('.')
beforeDecimal.take(3) + "." + afterDecimal.take(2)
}
// If there is no dot, just take the first 3 digits
else {
filteredChars.take(3)
}
}注意,我使用了kotlin函数character.isDigit(),而不是依赖硬编码的值。我添加了一个额外的检查,因为索引不是0,所以函数不允许第一个输入是.。我还添加了一张支票,不允许额外的.。
愿你平安✌
https://stackoverflow.com/questions/70058829
复制相似问题