简体   繁体   English

Jetpack 将数字输入输入到 TextField

[英]Jetpack Compose Number Input in to TextField

I am currently unable to capture user input in to a textfield when the KeyboardType of the keyboard is set to KeyboardType.Number.当键盘的 KeyboardType 设置为 KeyboardType.Number 时,我目前无法将用户输入捕获到文本字段中。

If the keyboard is set to KeyboardType.Text, the Textfield updates as expected, however when set to KeyboardType.Number, the Textfield fails to update.如果键盘设置为 KeyboardType.Text,Textfield 会按预期更新,但是当设置为 KeyboardType.Number 时,Textfield 无法更新。

Why is this?为什么是这样? and how can I change my code so that when the Textfield is clicked, a Number Keyboard is displayed,and, when numbers are pressed, the relevant numbers are updated in the Textfield.以及如何更改我的代码,以便在单击文本字段时显示数字键盘,并且当按下数字时,在文本字段中更新相关数字。

The following code DOES NOT update the textfield (When set to 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
    )

}

The following code does update the textfield (When set to KeyboardType.Text)...以下代码确实更新了文本字段(当设置为 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
    )

}

Many Thanks非常感谢

You are supposed to update text.value , not value.value there is a typo in your code change it to this.您应该更新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
    )

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM