Is it possible to get different colors in a TextField of Jetpack Compose?
Something like with the Text
composable with AnnotatedString
, but TextField doesn't allow AnnotatedString
as input value.
Image of normal Text composable with colors
You can use the VisualTransformation
in the TextField
.
TextField(
value = text,
onValueChange = { text = it },
visualTransformation = ColorsTransformation()
)
In the VisualTransformation
you can use AnnotatedString
to display the text with multiple styles.
Something like:
class ColorsTransformation() : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
return TransformedText(
buildAnnotatedStringWithColors(text.toString()),
OffsetMapping.Identity)
}
}
with:
fun buildAnnotatedStringWithColors(text:String): AnnotatedString{
val words: List<String> = text.split("\\s+".toRegex())// splits by whitespace
val colors = listOf(Color.Red,Color.Black,Color.Yellow,Color.Blue)
var count = 0
val builder = AnnotatedString.Builder()
for (word in words) {
builder.withStyle(style = SpanStyle(color = colors[count%4])) {
append("$word ")
}
count ++
}
return builder.toAnnotatedString()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With