Ajith M A
Ajith M A

Reputation: 5348

How to show Multiple color text in same Text view with Jetpack Compose?

I want to display text in multiple colors/style within same Text() component. How can i achieve this using Jetpack Compose?

Sample:

enter image description here

Upvotes: 9

Views: 8045

Answers (3)

Sayan Manna
Sayan Manna

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)
            )

enter image description here

Upvotes: 2

Mohd Qasim
Mohd Qasim

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

Ajith M A
Ajith M A

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

Related Questions