Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
)
like image 775
Henrique Tavolaro Avatar asked Mar 26 '21 19:03

Henrique Tavolaro


People also ask

How do I get TextField value in jetpack compose?

To read value entered in TextField in Android Compose, declare a variable, and assign this variable the value in the TextField whenever there is a change in the value. The same process holds for reading value entered in OutlineTextField composable.

How do I change Text size in compose?

To change font size of Text composable in Android Jetpack Compose, pass a required font size value for the optional fontSize parameter of Text composable. Make sure to import sp , as shown in the above code snippet, when you are assign fontSize property with scale-independent pixels.


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() }
                }
            }
        )
}
like image 155
Francesc Avatar answered Oct 22 '22 20:10

Francesc