Aghajari / AnnotatedText

A Jetpack Compose library to fully convert Android's Spanned into AnnotatedString
Apache License 2.0
60 stars 4 forks source link

How do I increase the font size via HTML for compose Text? #3

Open jayesh83 opened 11 months ago

Aghajari commented 11 months ago

Hello @jayesh83

Android's Html class does not offer direct support for setting an exact font size. Nevertheless, there are several alternative approaches to achieve the desired result:

  1. Relative Font Sizes: You can use HTML tags like <big> and <small> for relative font sizes. Additionally, heading tags such as <h1>, <h2>, etc., offer varying font sizes.
  2. Custom Tag Handler: For more precise control over font size, consider creating a custom tag handler. Here's an example:
class CustomTagHandler : Html.TagHandler {

    private var start = Stack<Int>()

    override fun handleTag(
        opening: Boolean,
        tag: String,
        output: Editable,
        xmlReader: XMLReader
    ) {
        if (tag.equals("test", ignoreCase = true)) {
            if (opening) {
                start.push(output.length)
            } else if (start.isNotEmpty()) {
                output.setSpan(
                    AbsoluteSizeSpan(30, true),
                    start.pop(),
                    output.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
    }
}

Usage:

@Preview
@Composable
fun TestPreview() {
    AnnotatedText(
        text = "Hello <test>World!</test>".fromHtml(
            tagHandler = CustomTagHandler()
        )
    )
}
jayesh83 commented 11 months ago

@Aghajari thanks for writing back.

one question, how can I make it configurable? Like for my use case I'd like to have say below custom tag

<fontSize value="18sp">12/20</fontSize> Orders Completed

can you help with like how do I also parse the value out of my custom handler?