Jetpack compose bold only string placeholder

Viewed 1825

I have a string resource like this

<string name="my_string">Fancy string with an %1$s placeholder</string>

and I would like to have this as output: "Fancy string with an amazing placeholder". Which is the string with the content of the placeholder in bold.

How can I get the desired output?

3 Answers

Finally I got the desired result with

val placeholder = "Amazing"

val globalText = stringResource(id = R.string.my_string, placeholder)

val start = globalText.indexOf(placeholder)
val spanStyles = listOf(
    AnnotatedString.Range(SpanStyle(fontWeight = FontWeight.Bold),
        start = start,
        end = start + placeholder.length
    )
)
Text(text = AnnotatedString(text = globalText, spanStyles = spanStyles))

Assuming that you are displaying this in a Text composable, do this. Make sure to include a backslash before the $ character:

Row(modifier = Modifier.wrapContentWidth()) {
    val s = LocalContext.current.getString(R.string.my_string)
    val p = s.indexOf("%1\$s")
    Text(s.substring(0, p))
    Text("amazing", fontWeight = FontWeight.Bold)
    Text(s.substring(p + 4))
}

Previous comments are too complicated. It's enough to use html tags in your string resource:

<string name="my_string">Fancy string with an <b>amazing</b> <i>placeholder</i></string>

If you are use Composable - you can use buildAnnotatedString for some cases. Documentation here

Text(
        buildAnnotatedString {
            withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
                append("W")
            }
            append("orld")
        }
    )
Related