androidkotlinandroid-jetpack-composeandroid-compose-textfield

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.


Solution

  • 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