Is there any out of the box solution for limiting the character size in TextField's ? I don't see any maxLength parameter like we had in XML.
You can use the onValueChange
parameter to limit the number of characters.
var text by remember { mutableStateOf("") }
val maxChar = 5
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
}
singleLine = true,
)
Then with M3 you can use the supportingText
attribute to display the counter text
.
Something like:
val maxChar = 5
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
},
modifier = Modifier.fillMaxWidth(),
supportingText = {
Text(
text = "${text.length} / $maxChar",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.End,
)
},
)
With M2 there isn't a built-in parameter.
In this case to display the counter text you can use something like:
val maxChar = 5
Column(){
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
},
singleLine = true,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "${text.length} / $maxChar",
textAlign = TextAlign.End,
style = MaterialTheme.typography.caption,
modifier = Modifier.fillMaxWidth().padding(end = 16.dp)
)
}