I have an Edittext (binding.text using view binding) that contains text styled with StyleSpans, i.e. bold and italics. To save the formatted text, I use HtmlCompat.toHtml(spannable) in Kotlin to convert it into HTML.
var htmlString = HtmlCompat.toHtml(SpannableString(binding.text.text), HtmlCompat.FROM_HTML_MODE_LEGACY)
However, the HTML returned is improperly nested if the text has bold and italics applied to it at the same time.
- Hello World: outputs
<p dir="ltr><b><i>Hello world</b></i></p>
As you can see, the tags applied are <b><i> </b></i> instead of <b><i> </i></b>.
When the text is not formatted, or either in bold or italics, then proper HTML is returned:
- Hello World: outputs
<p dir="ltr>Hello world</p> - Hello World: outputs
<p dir="ltr><b>Hello world</b></p>
I suppose the function likes to put <b> and </b> first as opposed to <i> and </i>, but this causes weird results as shown.
So the question: How do I get the function to return correctly formatted HTML?