Reputation: 5348
I want to display text in multiple colors/style within same Text() component. How can i achieve this using Jetpack Compose?
Sample:
Upvotes: 9
Views: 8045
Reputation: 679
You can use a List of pairs to define the text-color pairs. This way, you can display any number of styled text segments with their respective colors.
@Composable
fun MultiColorText(vararg textWithColors: Pair<String, Color>) {
Text(buildAnnotatedString {
textWithColors.forEach { (text, color) ->
withStyle(style = SpanStyle(color = color)) {
append(text)
}
}
})
}
now pass any number of text-color pairs to create a multi-styled text view.
MultiColorText(
Pair("OS Version: ", Color.DarkGray),
Pair("Android 12", Color.Blue),
Pair("\n\nJetpack Compose", Color.Black),
Pair(" is awesome!", Color.Magenta)
)
Upvotes: 2
Reputation: 1010
and you can check this snippet of code as well
Row(horizontalArrangement = Arrangement.Center) {
Text(text = "Version:",color = Color.Black)
Text(text = "Android 12",color = Color.Blue)
}
Upvotes: -3
Reputation: 5348
This can be easily achieved using an AnnotatedString in Compose. A custom composable can be created which takes the two colors and strings as parameter like below.
@Composable
fun MultiStyleText(text1: String, color1: Color, text2: String, color2: Color) {
Text(buildAnnotatedString {
withStyle(style = SpanStyle(color = color1)) {
append(text1)
}
withStyle(style = SpanStyle(color = color2)) {
append(text2)
}
})
}
This composable can then be used in your code as below.
MultiColorText("OS Version: ", Color.DarkGray, "Android 12", Color.Blue)
You may add more customization and different styles to different parts of the string.
Reference: https://developer.android.com/jetpack/compose/text#multiple-styles
Upvotes: 25