How do I set the input type to Integer in jetpack Compose?

Viewed 3768

How can I make the TextField accept only integers as input and how can I limit the number of digits to 2?

I have already set keyboard as below but this allows to input decimals and I need only positive Integers

keyboardOptions = KeyboardOptions(
    keyboardType = KeyboardType.Number
)
1 Answers

The TextField does not do any filtering by itself, you have to do the filter by using its callback. For instance,

AppTheme {
    var text by remember {
        mutableStateOf("")
    }
    Surface(modifier = Modifier.width(320.dp)) {
        TextField(
            value = text,
            onValueChange = { value ->
                if (value.length <= 2) {
                    text = value.filter { it.isDigit() }
                }
            }
        )
}
Related