OutputTransformation


A function (transformOutput) that transforms the text presented to a user by a BasicTextField.

Summary

Public functions

Unit

Given a TextFieldBuffer that contains the contents of a TextFieldState, modifies the text.

Cmn

Public functions

transformOutput

fun TextFieldBuffer.transformOutput(): Unit

Given a TextFieldBuffer that contains the contents of a TextFieldState, modifies the text. After this function returns, the contents of the buffer will be presented to the user as the contents of the text field instead of the raw contents of the TextFieldState.

Use this function to change the visual and semantics representation of the text. For example, a phone number field can format the raw input by adding parentheses and white spaces in between characters.

The result of this transformation is purely representational and does not affect the contents of TextFieldState.

Selection and cursor positions are managed internally by BasicTextField. If there's a range of inserted characters via this OutputTransformation, selection or cursor never goes in between these inserted characters.

Note that this transformation is called every time a new text needs to be displayed. This implies that the contents of TextFieldBuffer will always be what the TextFieldState holds currently. All the changes made here are discarded after text is presented to the user.

import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.input.InputTransformation
import androidx.compose.foundation.text.input.OutputTransformation
import androidx.compose.foundation.text.input.TextFieldBuffer
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.foundation.text.input.insert
import androidx.compose.foundation.text.input.maxLength
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.foundation.text.input.then
import androidx.compose.material.Text
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember

@Stable
data class PhoneNumberOutputTransformation(private val pad: Boolean) : OutputTransformation {
    override fun TextFieldBuffer.transformOutput() {
        if (pad) {
            // Pad the text with placeholder chars if too short.
            // (___) ___-____
            val padCount = 10 - length
            repeat(padCount) { append('_') }
        }

        // (123) 456-7890
        if (length > 0) insert(0, "(")
        if (length > 4) insert(4, ") ")
        if (length > 9) insert(9, "-")
    }
}

val state = rememberTextFieldState()
BasicTextField(
    state,
    inputTransformation =
        InputTransformation.maxLength(10).then {
            if (!TextUtils.isDigitsOnly(asCharSequence())) {
                revertAllChanges()
            }
        },
    outputTransformation = PhoneNumberOutputTransformation(false)
)