kotlin 我怎样才能把数字的限制在android jetpack compose的文本字段?

wyyhbhjk  于 2023-03-09  发布在  Kotlin
关注(0)|答案(2)|浏览(190)

我在android jetpack compose中有一个文本字段,所以我想把数字限制,例如;用户只能写从1到10的数字,有可能在jetpack compose中完成吗?

@Preview(showBackground = true)
@Composable
fun OutlinedTextFieldComposable() {
    var text by remember { mutableStateOf("") }
    OutlinedTextField(
        value = text,
        onValueChange = { text = it },
        label = { Text("Label") },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
 
}
kyks70gy

kyks70gy1#

你可以在onValueChange中设置一个条件,如下所示:

@Preview(showBackground = true)
@Composable
fun OutlinedTextFieldComposable() {
    var text by remember { mutableStateOf("") }
    val maxNumbers = 10
    OutlinedTextField(
        value = text,
        onValueChange = { if (it.toInt() <= maxNumbers) text = it },
        label = { Text("Label") },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
 
}
0yycz8jy

0yycz8jy2#

BasicTextField(
                value = phoneNumber,
                onValueChange = { enterValue ->
                    phoneNumber =
                        if (enterValue.length <= 10) enterValue else enterValue.substring(0, 10)
                },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                
            )

享受

相关问题