title: Android: How to convert HTML string to Spanned to display in TextView (MUST work on API < 24)
body: <p>For my app, I need to display HTML that contains spans (with <strong>background-color</strong>) to a <code>Spanned</code> such that it can be displayed on a <code>TextView</code>, as Android's <code>TextView</code> does not support the <code>span</code> tag. I have first tried converting the <code>String</code> to a <code>SpannableStringBuilder</code>, and then retrieving the HTML encoded string from the casted string (<code>Spanned</code>). I need this to work on API 22-23, and thus, I <strong>cannot simply use fromHTML</strong> as <code>fromHTML</code> does not support <code>span</code> for API below 24. I am writing a function called <code>fromHTML</code> to accomplish this:</p>
  
  <p>Example of the input to <code>fromHTML</code> (the input can be any string with spans):</p>
  
  <pre><code>Not highlighted string&lt;span style=\"background-color: #FF8983\"&gt;Highlighted string&lt;/span&gt; 
  not highlighted string &lt;span style=\"background-color: #FF8983\"&gt;Highlighted string&lt;/span&gt; 
  </code></pre>
  
  <p>Below is my code:</p>
  
  <pre><code>private fun fromHtml(source:String):Spanned {
      var htmlText:SpannableStringBuilder = source as SpannableStringBuilder;
      var htmlEncodedString:String = Html.toHtml(htmlText);
  
      if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N)
      {
          return Html.fromHtml(htmlEncodedString, Html.FROM_HTML_MODE_LEGACY)
      }
      else
      {
          return Html.fromHtml(htmlEncodedString)
      }
  }
  </code></pre>
  
  <p>However, I get the following error:</p>
  
  <blockquote>
    <p>java.lang.ClassCastException: java.lang.String cannot be cast to
    android.text.SpannableStringBuilder</p>
  </blockquote>
  
  <p>How do I convert an HTML string to a Spanned object to display on a TextView (<strong>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</strong>?</p>