Wednesday, 8 January 2020

Android: How to convert HTML string to Spanned to display in TextView (MUST work on API < 24)

For my app, I need to display HTML that contains spans (with background-color) to a Spanned such that it can be displayed on a TextView, as Android's TextView does not support the span tag. I have first tried converting the String to a SpannableStringBuilder, and then retrieving the HTML encoded string from the casted string (Spanned). I need this to work on API 22-23, and thus, I cannot simply use fromHTML as fromHTML does not support span for API below 24. I am writing a function called fromHTML to accomplish this:

Example of the input to fromHTML (the input can be any string with spans):

Not highlighted string<span style=\"background-color: #FF8983\">Highlighted string</span> 
not highlighted string <span style=\"background-color: #FF8983\">Highlighted string</span> 

Below is my code:

private fun fromHtml(source:String):Spanned {
    var htmlText:SpannableStringBuilder = source as SpannableStringBuilder;
    var htmlEncodedString:String = Html.toHtml(htmlText);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
    {
        return Html.fromHtml(htmlEncodedString, Html.FROM_HTML_MODE_LEGACY)
    }
    else
    {
        return Html.fromHtml(htmlEncodedString)
    }
}

However, I get the following error:

java.lang.ClassCastException: java.lang.String cannot be cast to android.text.SpannableStringBuilder

How do I convert an HTML string to a Spanned object to display on a TextView (I need this program to work on API 22-23, and on API 22-23, span is not supported so I cannot just use a simple fromHTML conversion?



from Android: How to convert HTML string to Spanned to display in TextView (MUST work on API < 24)

No comments:

Post a Comment