Jetpack Compose文本框中的数字输入

8

当键盘类型为KeyboardType.Number时,我目前无法捕获用户对文本字段的输入。

如果键盘类型设置为KeyboardType.Text,则文本字段会按预期更新,但是当设置为KeyboardType.Number时,文本字段不会更新。

为什么会这样?我该如何更改代码,以便当单击文本字段时显示数字键盘,并在按下数字时将相应数字更新到文本字段中。

以下代码不会更新文本字段(当设置为KeyboardType.Number时)...

@Composable
fun MyNumberField() {

    var text = remember { mutableStateOf("")}

    val change : (String) -> Unit = { it ->
        value.value = it
    }

    TextField(
        value = text.value,
        modifier = Modifier.fillMaxWidth(),
        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
        onValueChange = change
    )

}


以下代码确实会更新文本字段(当设置为KeyboardType.Text时)...
@Composable
fun MyNumberField() {

    var text = remember { mutableStateOf("")}

    val change : (String) -> Unit = { it ->
        text.value = it
    }

    TextField(
        value = value.value,
        modifier = Modifier.fillMaxWidth(),
        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Text),
        onValueChange = change
    )

}


非常感谢。

捕获用户输入到文本字段中是什么意思? - Gabriele Mariotti
@GabrieleMariotti 当键盘类型设置为KeyboardType.Number时,用户输入数字时'text'的值不会更新,但是当键盘类型设置为KeyboardType.Text时,该值会更新。 - olistocks98
你使用的Compose版本是哪个?它应该在beta07上无问题运行。 - Gabriele Mariotti
@GabrieleMariotti 哦,是的!非常感谢,我还在使用Beta01版本! - olistocks98
更新到最新版(beta7)解决了你的问题吗? - Koch
1个回答

14
你应该更新text.value,而不是value.value。你的代码中有一个拼写错误,请更正成这样。
@Composable
fun MyNumberField() {

    var text = remember { mutableStateOf("")}

    val change : (String) -> Unit = { it ->
        value.value = it    // you have this which is not correct and I don't think it even compiled
        text.value = it  // it is supposed to be this 
    }

    TextField(
        value = text.value,
        modifier = Modifier.fillMaxWidth(),
        keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
        onValueChange = change
    )

}

它允许输入点和逗号。 - user924

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接