79632255

Date: 2025-05-21 15:02:41
Score: 0.5
Natty:
Report link

Although my approach doesn't use HTML tags like the author needs, I want to leave this answer here because it might help others who essentially want to have styled text defined in string resources, and would rather configure the text somewhere else, like in a mapper or the viewModel, instead of cluttering the composables with buildAnnotatedString { ... } calls (because we want to keep the text reactive to locale changes)

I created a library that solves this issue for me, feel free to use it: https://github.com/radusalagean/ui-text-compose

Example:

strings.xml

<resources>
    <string name="greeting">Hi, %1$s!</string>
    <string name="shopping_cart_status">You have %1$s in your %2$s.</string>
    <string name="shopping_cart_status_insert_shopping_cart">shopping cart</string>

    <plurals name="products">
        <item quantity="one">%1$s product</item>
        <item quantity="other">%1$s products</item>
    </plurals>
</resources>

You can create text blueprints like this:

val uiText = UIText {
    res(R.string.greeting) {
        arg("Radu")
    }
    raw(" ")
    res(R.string.shopping_cart_status) {
        arg(
            UIText {
                pluralRes(R.plurals.products, 30) {
                    arg(30.toString()) {
                        +SpanStyle(color = CustomGreen)
                    }
                    +SpanStyle(fontWeight = FontWeight.Bold)
                }
            }
        )
        arg(
            UIText {
                res(R.string.shopping_cart_status_insert_shopping_cart) {
                    +SpanStyle(color = Color.Red)
                }
            }
        )
    }
}

And then use them in your Composable:

Text(uiText.buildAnnotatedStringComposable())

enter image description here

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Radu S.