My 100th Post! 🎉
Problem:
I needed to be able to display parsed, dynamically fetched html anchor tags in an Android TextView. I struggled with a few of these concepts and some of the requirements between various API levels.
Solution:
Begin by parsing the html text into a Spanned. I wrote a private helper function to accomplish this:
1 2 3 4 5 6 7 | private Spanned parseHtmlText (final String text) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT); } else { return Html.fromHtml(text); } } |
To make this work on Nougat and above you need to provide the following flag: Html.FROM_HTML_MODE_COMPAT. Set the TextView text using the Spanned return value. Use the Linkify utility (Linkify API Reference), set the MovementMethod and linksClickable:
1 2 3 4 5 6 | TextView textView; textView.setText(parseHtmlText("Unlinked text. <a href="\"https://www.rileymacdonald.ca\"">Linked Text</a>. More unlinked text")); Linkify.addLinks(textView, Linkify.ALL); textView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setLinksClickable(true); // or using style/XML true or XML linksClickable="true" |
Any html anchors should now be parsed and displayed as expected.
Caveats
I’ve found the above approach to work however when combined with the following xml tags/styles it fails (text is shown but it isn’t clickable/linked:
textIsSelectable="true"ortrueautoLink="all"orall