8

I am currently unable to capture user input in to a textfield when the KeyboardType of the keyboard is set to 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.

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)...

@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)...

@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

olistocks98
  • 483
  • 1
  • 5
  • 7

1 Answers1

11

You are supposed to update text.value, not value.value there is a typo in your code change it to this.

@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
    )

}
AgentP
  • 6,261
  • 2
  • 31
  • 52