I have a Text Field in android jetpack compose, which used to get number from user including floating points. How to prevent user from entering 2 dots in the input. For Eg: Number should be 56.54,.266, 367.5
Should not be like this: 34.3.5
CodePudding user response:
I’m assuming you are using a TextField
composable. You can set the keyboard options to a type of Number.
TextField(
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
CodePudding user response:
You can use onValueChange
of TextField
to filter the text:
@Composable
fun MyTextField(
) {
var text by remember { mutableStateOf("") }
TextField(
keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
value = text,
onValueChange = {
val newString = it.filter { char ->
char == ".".first()
}
if (newString.length <= 1)
text = it
}
)
}