如何使 TextField 僅接受整數作為輸入,以及如何將小數點前的位數限制為 3,將小數點后的位數限制為 2?
例如 NNN.NN,其中 N 是數字。
uj5u.com熱心網友回復:
第一步是設定keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)TextField。這將在 TextField 聚焦時打開數字小鍵盤。
現在的問題是 TextField 本身不做任何驗證(不像 EditText with inputType="number")。用戶可以輸入鍵盤上的任何字符(如逗號、空格、破折號,甚至多個小數)。您需要自己完成所有這些驗證。
試試這個代碼:
var number by remember { mutableStateOf("") }
TextField(
value = number,
onValueChange = { number = getValidatedNumber(it) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
fun getValidatedNumber(String text): 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”并且用戶將游標放在小數點后并洗掉小數點。在這種情況下,新文本將變為“123”,即“45”將被洗掉,因為“12345”打破了“小數限制前的 3 位數字”。
- 如果當前文本是“123”并且用戶將游標放在開頭并鍵入“4”,則下一個文本將是“412”。“3”將被洗掉。
對于用戶更改游標位置和輸入內容的這些極端情況,您必須決定正確的行為應該是什么(就像在我的第一個示例中,您可能選擇不允許洗掉小數點并保留原始文本)。您必須getValidatedNumber根據您的確切要求在函式中添加此類條件。我有時在這里使用的一種解決方法是禁用游標位置更改,即游標將始??終保留在末尾并且不能被帶到任意索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363886.html
標籤:安卓工作室 科特林 android-jetpack-compose
上一篇:我在KaptDebugKotlin中遇到錯誤。我在gradle檔案中有更新版本的依賴項。仍然面臨這個問題
下一篇:組合存盤庫邏輯的最佳方法
