Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 617
Nicola De Fiorenze Avatar asked Nov 18 '25 16:11

Nicola De Fiorenze


2 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))
like image 113
Nicola De Fiorenze Avatar answered Nov 21 '25 05:11

Nicola De Fiorenze


Text(
    text = buildAnnotatedString {
        withStyle(style = SpanStyle(color = Color.Blue)) {
            append("H")
        }
        append("ello ")

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

enter image description here

src - github or developers.

like image 28
Ravikant sahu Avatar answered Nov 21 '25 05:11

Ravikant sahu