androidandroid-jetpack-compose

Jetpack compose bold only string placeholder


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?


Solution

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