You can use AnnotatedString to append each word/section with it's own style or to add different style at any index which is great if you're using a string resource.
For the hello world example you could construct something like this:
val annotatedString = buildAnnotatedString {
val str = "Hello World" // or stringResource(id = R.string.hello_world)
val boldStr = "Hello" // or stringResource(id = R.string.hello)
val startIndex = str.indexOf(boldStr)
val endIndex = startIndex + boldStr.length
append(str)
addStyle(style = SpanStyle(color = Color.Red), start = startIndex, end = endIndex)
}
Text(
text = annotatedString,
)
Using addStyle
in this way allows us to do some fun things like adding multiple styles to the same text
val annotatedString = buildAnnotatedString {
val str = "Hello Wonderful World" // or stringResource(id = R.string.hello_world)
val boldStr = "Wonderful World" // or stringResource(id = R.string.world)
val startIndex = str.indexOf(boldStr)
val endIndex = startIndex + boldStr.length
append(str)
addStyle(style = SpanStyle(color = Color.Red), start = startIndex, end = endIndex)
val italicsStr = "Wonderful"
val italicsStartIndex = str.indexOf(italicsStr)
val italicsEndIndex = startIndex + italicsStr.length
addStyle(style = SpanStyle(fontStyle = FontStyle.Italic), start = italicsStartIndex, end = italicsEndIndex)
}
Text(
text = annotatedString,
style = TextStyle(fontWeight = FontWeight.Bold),
color = Color.Blue,
)