Issue
I want to display text in multiple colors/style within same Text() component. How can i achieve this using Jetpack Compose?
Sample:
src="https://i.stack.imgur.com/ATJxI.png" alt="enter image description here" />
Solution
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
Answered By - Ajith M A
Answer Checked By - Mildred Charles (JavaFixing Admin)