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

Viewed 275

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

1 Answers

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

Related