Question

TextField maxLength - Android Jetpack Compose

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.

 46  38604  46
1 Jan 1970

Solution

 92

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,
        )
    },
)

enter image description here

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)
    )
}

enter image description here

2021-04-17

Solution

 14

You can use take function - here documentation

onValueChange = { onYearChanged(it.take(limitNum)) })

For example, if you will use it in function.

const val limitNum = 4

@Composable
fun YearRow(
  modifier: Modifier = Modifier,
  year: Int, 
  onYearChanged: (String) -> Unit,
) {
  OutlinedTextField(
    modifier = modifier,
    value = if (year == 0) "" else "$year",
    onValueChange = { onYearChanged(it.take(limitNum)) },
  )
}
2022-11-29