Function

maxLength

Returns InputTransformation that rejects input which causes the total length of the text field to be more than maxLength characters.

BasicTextFieldInputTransformationMaxLengthCustom

@Sampled
@Composable
fun BasicTextFieldInputTransformationMaxLengthCustom() {
    val state = remember { TextFieldState() }
    BasicTextField(
        state,
        inputTransformation =
            object : InputTransformation {
                override fun SemanticsPropertyReceiver.applySemantics() {
                    // The output transformation formats "1234567890" to "(123) 456-7890",
                    // which is 14 characters long. We set the accessibility maximum length
                    // to 14 so screen readers announce the correct limit.
                    maxTextLength = 14
                }

                override fun TextFieldBuffer.transformInput() {
                    if (length > 10) {
                        delete(10, length)
                    }
                }
            },
        outputTransformation =
            OutputTransformation {
                if (length > 0) insert(0, "(")
                if (length > 4) insert(4, ") ")
                if (length > 9) insert(9, "-")
            },
    )
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: