Tag Archives: textview

Android HTML in a TextView

The documentation on supported HTML tags and HTML usage is lacking in general so after some trial & error with some googling I got things to finally work correctly including links.

In my case I was working with text from a resource file, specifically items in a string-array. Here’s a snippet from my :


<item>
      <![CDATA[
            <p>The main purpose of this app is to help you get things done by focusing on the now. For more info on the techniques used and how you can get involved please visit the <a href=\"http://slamtastic.me/work/do-now/\">Do Now site</a> and <a href=\"http://slamtastic.me/category/productivity/\">Blog</a>. You can also follow on <a href=\"http://twitter.com/do_nowapp\">Twitter</a> and/or join the <a href=\"https://plus.google.com/communities/116626905003478130395\">G+ community</a> for feedback and beta access.</p>
            <br/>
            <p>It’s basically split into two parts: your ‘Planned’ items and your ‘Unplanned’ items. For more info, see the sections below about each list. Since syncing with Google Tasks is possible, this app can be used along with another app that focuses on long term tasks and goals as long as that app also syncs with Google Tasks.</p>
      ]]>
</item>

Notice the <![CDATA[ ]]> tag that surrounds the HTML text. You’ll need this unless your text is very basic and no parsing is needed. The other thing to notice is escaping the quotes in the anchor tags. Without this, when the string is parsed, you’ll end up with href=yoururl which is invalid and will not work.

Next is loading the text. You’ll need to use the HTML class to parse the string:

Html.fromHtml(someHtmlText)

You can set that as the text for TextView or save it to a Spanned type variable then set that as the text.

After setting the text using textView.setText(parsedHTML) use:


textView.setMovementMethod(LinkMovementMethod.getInstance());

Your TextView should look like this (noting the android:linksClickable and android:textColorLink attributes):


<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/text_primary"
        android:layout_marginBottom="10dp"
        android:linksClickable="true"
        android:textColorLink="@color/primary"
        android:id="@+id/help_child_description"/>

Now your HTML should be parsed correctly and links working.