use*_*924 3 android android-jetpack-compose android-compose-textfield
所以我只需要允许在字段中输入数字。
我配置了TextField
:
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number
)
Run Code Online (Sandbox Code Playgroud)
但它仍然允许我输入小数分隔符(逗号和点)
所以我看不出KeyboardType.Number
和之间有什么区别KeyboardType.Decimal
,它们的工作原理完全相同......
数字
@Stable
public final val Number: KeyboardType
A keyboard type used to request an IME that is capable of inputting digits. IME may provide inputs other than digits but it is not guaranteed.
Run Code Online (Sandbox Code Playgroud)
十进制
@Stable
public final val Decimal: KeyboardType
A keyboard type used to request an IME that is capable of inputting decimals. IME should explicitly provide a decimal separator as input, which is not assured by KeyboardType.Number.
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?
正如本期所解释的:
当键盘类型设置为 Number 时,大多数键盘都会显示小数点分隔符。但是,键盘可能期望
TYPE_NUMBER_FLAG_DECIMAL
inputType 中的标志实际显示小数点分隔符的键。
此更改添加了一个名为 Decimal 的新 KeyboardType,它显式设置了所需的标志。对于大多数键盘和 OEM,数字和小数的行为本质上是相同的。
您可以使用正则表达式模式限制允许的字符。
就像是:
val pattern = remember { Regex("^\\d+\$") }
TextField(
value = text,
onValueChange = {
if (it.isEmpty() || it.matches(pattern)) {
text = it
}
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1480 次 |
最近记录: |