1

I have a textfield in android jetpack compose, so I want to put limit for numbers, for example; user can write only numbers from 1 to 10, is it possible to do it in jetpack compose?

@Preview(showBackground = true)
@Composable
fun OutlinedTextFieldComposable() {
    var text by remember { mutableStateOf("") }
    OutlinedTextField(
        value = text,
        onValueChange = { text = it },
        label = { Text("Label") },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
 
}
Huma33
  • 59
  • 7

2 Answers2

1

You can make a condition for that inside onValueChange like this:

@Preview(showBackground = true)
@Composable
fun OutlinedTextFieldComposable() {
    var text by remember { mutableStateOf("") }
    val maxNumbers = 10
    OutlinedTextField(
        value = text,
        onValueChange = { if (it.toInt() <= maxNumbers) text = it },
        label = { Text("Label") },
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number))
 
}
Mohamed Rejeb
  • 2,281
  • 1
  • 7
  • 16
  • tnx so much for ur answer, I mean if I put 11 it is not able to write, I want to just put number 1,2,3,...10, but user will not put 11 – Huma33 Jun 22 '22 at 08:44
  • Yes that's what is going to happen – Mohamed Rejeb Jun 22 '22 at 08:50
  • it put the text field limit like numbers limit, for example if u put val maxNumbers = 2, u can only typing 99 max, u cannot write 100, but this question not about it, here I mean user only can write limited numbers like 1,2,3,4,5,...10. user will not able to write 11,12,13... – Huma33 Jun 22 '22 at 09:07
  • There's a KeyboardType.Digit. Otherwise, you need to check the number so that if it's bigger than 10, it won't be updated. – c-an Mar 24 '23 at 03:47
0
BasicTextField(
                value = phoneNumber,
                onValueChange = { enterValue ->
                    phoneNumber =
                        if (enterValue.length <= 10) enterValue else enterValue.substring(0, 10)
                },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                
            )

enjoy