What is the alternative for android:maxLength in O...
# compose
c
What is the alternative for android:maxLength in OutlinedTextField?
2
c
I tried to do this recently and couldn't find anything in the docs. Only things available were maxLines
n
Copy code
TextField(
    label = { Text("Name") },
    value = nameState,
    onValueChange = { s: String ->
        if (s.length < 50) nameState = s
    }
)
🤷‍♂️
c
@nglauber it's actually quite nice to see how quick it is to whip something like that up. 😄 I think a part of the material input fields on material.io though shows a character count which would be nice to have out of the box... but this is def nice too.
n
I partially agree. Have more features out of the box is a good thing, however it adds more complexity to customize a few things… For instance imagine that you want a different font color if the max length is about to be reached out. How could you do that if this feature is out of the box? btw… it’s also easy to show this char count 😛
Copy code
val maxLength = 20
Column {
    OutlinedTextField(
        label = { Text("Name") },
        value = nameState,
        onValueChange = { s: String ->
                        if (s.length <= maxLength) {
                            nameState = s
                        }
        }
    )
    Text(
        "${nameState.length} / $maxLength",
        fontSize = 12.sp,
        modifier = Modifier.align(Alignment.End)
    )
}
You can put this in a Composable function an boom! You have a custom TextField 😊