視圖模型
fun changeQty(textField: TextFieldValue) {
val temp1 = textField.text
Timber.d("textField: $temp1")
val temp2 = temp1.replace("[^\\d]".toRegex(), "")
Timber.d("temp2: $temp2")
_qty.value = textField.copy(temp2)
}
文本域
OutlinedTextField(
modifier = Modifier
.focusRequester(focusRequester = focusRequester)
.onFocusChanged {
if (it.isFocused) {
keyboardController?.show()
}
},
value = qty.copy(
text = qty.text.trim()
),
onValueChange = changeQty,
label = { Text(text = qtyHint) },
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
save()
onDismiss()
}
)
)
設定 KeyboardType.Number,它顯示 1,2,3,4,5,6,7,8,9 和 , 。- 空間。我只想得到像 -10 或 10 或 0 這樣的整數。但我輸入 , 或 . 或 -(不是前面的標志),它按原樣顯示。
例如)打字= -10------
希望 = -10
顯示 = -10---------
我把正則運算式放在
val temp2 = temp1.replace("[^\\d]".toRegex(), "")
但是,它似乎不起作用。我怎樣才能只得到整數(也是負整數)?
uj5u.com熱心網友回復:
使用此正則運算式(?<=(\d|-))(\D )替換所有非數字字符,除了 first -。
fun getIntegersFromString(input: String): String {
val pattern = Regex("(?<=(\\d|-))(\\D )")
val formatted = pattern.replace(input, "")
return formatted
}
在這里檢查
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/465831.html
標籤:正则表达式 科特林 android-jetpack-compose
