olistocks98
olistocks98

Reputation: 583

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.

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

Upvotes: 15

Views: 21997

Answers (2)

Pacheco
Pacheco

Reputation: 151

I would go a step further and use a MutableIntState and also check that all entered text is an Int.

@Composable
fun MyNumberField() {

    var number = remember { mutableIntStateOf("")}

    val change : (String) -> Unit = { it ->
        number = it.toIntOrNull() ?: number 
    }
 ...

Upvotes: 2

AgentP
AgentP

Reputation: 7220

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
    )

}

Upvotes: 21

Related Questions