Search code examples
kotlinandroid-jetpack-composeandroid-jetpack-compose-text

How to save to TextField database transformed with visualTransformation


How to save to TextField database transformed with visualTransformation?

I have the following code:

var text by remember { mutableStateOf("") }
TextField(
    value = text,
    visualTransformation = DateTransformation(),
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
    onValueChange = {
        if (it.length < 9) text = it
    }
)
Log.i("DATA",text)

the format is XX/XX/XXXX but when I send it to the database it loses the format and is XXXXXXXX


Solution

  • You can apply same transformations your VisualTransformation does using filter like this:

    val visualTransformation: VisualTransformation = remember { DateTransformation() }
    var text by remember { mutableStateOf("") }
    Button(onClick = {
        val transformedText = visualTransformation.filter(AnnotatedString(text)).text.text
        // save to DB
    }) {
    
    }
    TextField(
        value = text, onValueChange = { text = it },
        visualTransformation = visualTransformation
    )