androidandroid-jetpack-composetextfieldcompose-multiplatformjetbrains-compose

How to add uneditable postfix (suffix) to TextField in Jetpack Compose?


How can I add a suffix to TextField input that flows (moves) with the user input text?


Solution

  • With M3 starting from the 1.1.0-alpha06 you can use the suffix attribute:

        TextField(
            value = text,
            onValueChange = { text = it },
            suffix = { Text ("€") }
        )
    

    enter image description here

    Before M3 1.1.0-alpha06 or with M2 or you can use the visualTransformation attribute.

    Something like:

    TextField(
        value = text,
        onValueChange = { text = it },
        singleLine = true,
        visualTransformation = SuffixTransformation(" €"),
    )
    
    class SuffixTransformation(val suffix: String) : VisualTransformation {
        override fun filter(text: AnnotatedString): TransformedText {
    
            val result = text + AnnotatedString(suffix)
    
            val textWithSuffixMapping = object : OffsetMapping {
                override fun originalToTransformed(offset: Int): Int {
                    return offset
                }
    
                override fun transformedToOriginal(offset: Int): Int {
                    if (text.isEmpty()) return 0
                    if (offset >=  text.length) return text.length                    return offset
                }
            }
    
            return TransformedText(result, textWithSuffixMapping )
        }
    }
    

    enter image description here

    If you have the placeholder you can put a condition in the visualTransformation attribute.

    Something like:

    TextField(
        value = text,
        onValueChange = { text = it },
        singleLine = true,
        visualTransformation = if (text.isEmpty())
            VisualTransformation.None
        else
            SuffixTransformation(" €"),
        placeholder = { Text("Placeholder") }
    )