https://kotlinlang.org logo
#compose
Title
# compose
j

jasu

11/09/2023, 5:41 AM
How can I change font-size from html for Compose Text? I've JSON like
Copy code
"label": "<span style=\"font-size: 12px;\">14/20</span> Orders completed"
and would like to render text where 14/20 is bigger than rest
a

ascii

11/09/2023, 1:36 PM
Maybe there's some libraries that already do this for you, but if your use-case deals with very limited HTML, it's worth it to write your own HTML-Compose interop:
Copy code
buildAnnotatedString {
    // Defer to platform via androidx.core.text.HtmlCompat
    append(HtmlCompat.fromHtml(html, flags).toString())

    // Apply default span & paragraph styles
    val length = spanned.length
    val textStyle = LocalTextStyle.current
    val spanStyle = textStyle.toSpanStyle()
    addStyle(spanStyle, 0, length)
    addStyle(textStyle.toParagraphStyle(), 0, length)

    val defaultFontSize = spanStyle.fontSize
    spanned.getSpans<Any>().forEach { span ->
        val start = spanned.getSpanStart(span)
        val end = spanned.getSpanEnd(span)

        when (span) {
            is RelativeSizeSpan -> SpanStyle(fontSize = defaultFontSize * span.sizeChange)
            // ^ this is what you want
            // … other spans
        }.let {
            addStyle(it, start, end)
        }
    }
}
And if you control the HTML in your response, I'd suggest going for
font-size: larger
or something like that. Leave it to the client (app or website) to style it accordingly. Or you know, you could refactor your response to not be in HTML at all. The example you gave doesn't need HTML (return numbers & suffix string as separate fields).
j

jasu

11/10/2023, 1:03 PM
No the problem is, numbers and text make up a sentence. They're localised. In some langs, numbers will be in between and in some it'll be at last right.
We've tried with RelativeSizeSpan but then again its like its not full-proof. Was looking at solution which works uniformly. there's also one span
AbsoluteSizeSpan
any idea about that?
5 Views