Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jetpack compose text visual transformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.AnnotatedString
/**
* Visually transform a string as YYYY-MM-DD.
*/
object DateVisualTransformation : VisualTransformation {
fun transform(original: String): String {
val trimmed: String = original.take(8)
if (trimmed.length < 4) return trimmed
if (trimmed.length == 4) return "$trimmed-"
val (year, monthAndOrDate) = trimmed.chunked(4)
if (trimmed.length == 5 ) return "$year-$monthAndOrDate"
if(trimmed.length == 6) return "$year-$monthAndOrDate-"
val (month, date) = monthAndOrDate.chunked(2)
return "$year-$month-$date"
}
override fun filter(text: AnnotatedString): TransformedText {
return TransformedText(AnnotatedString(transform(text.text)),
object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
if (offset <= 3) return offset
if (offset <= 5) return offset + 1
if (offset <= 7) return offset + 2
return 10
}
override fun transformedToOriginal(offset: Int): Int {
if (offset <= 4) return offset
if (offset <= 7) return offset - 1
if (offset <= 10) return offset - 2
return 8
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment