I am trying to set a limit for the max characters count in a TextField. This is what I tried:
var text by remember { mutableStateOf("") }
val maxLength = 40
TextField(
value = text,
onValueChange = {
text = it.take(maxLength)
}
)
Here's the problem:
- When I exceed the limit, the entire text suddenly gets cleared.
- This happens only once i.e. when I retype and exceed limit it just stops there (which is the desired behavior)
- 40 seems like a magic number here, because for maxLength = 39 or lower, everything works fine. When I set the limit to 40 or higher, I see this strange behavior. (This magic number doesn't seem to depend upon text field width as I experimented with both portrait and landscape mode and the result was same)
How to get rid of this behavior? What's the right way to set a max length for TextField text?
