How can I make links in fromHTML clickable? (Android)

HtmlAndroidHyperlink

Html Problem Overview


This seems like a trivial problem, but it has me kind of stumped. I want to load an HTML string using Html.fromHtml(), and have any links in the string to be clickable and open in the browser.

Basic example:

textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));

With this snippet, the text is formatted as if it were a link (blue, underlined), but it's not clickable. I tried Linkify, but it only seems to work with links that are not HTML-based.

Any suggestions?

Html Solutions


Solution 1 - Html

As I assumed, the solution was trivial:

textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
textView.setMovementMethod(LinkMovementMethod.getInstance());

The second line somehow activates the link behavior, although I'm not quite sure how. The same question is addressed over at [Google Code][1].

[1]: http://code.google.com/p/android/issues/detail?id=2219 "Google Code"

Solution 2 - Html

As mentioned in other answers, a way forward is to use:

xtView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
textView.setMovementMethod(LinkMovementMethod.getInstance());

However, this won't work if you have ANY android:autoLink value set, not just 'web' as other comments seem to suggest. So that means you can use this solution to linkify URLs at the expense of having phone, email and maps being disabled/unlinked.

Solution 3 - Html

The javadoc of the LinkMovementMethod says that it > Supports clicking on links with DPad Center or Enter.

So it makes sense that works that way.

And confirmed, with 4.2.2 works like charm with just the

textView.setMovementMethod(LinkMovementMethod.getInstance());

Solution 4 - Html

It should be this way:

textView.setText(Html.fromHtml("<a href=\"http://www.google.com\">This is a link</a>"));
textView.setAutoLinkMask(Linkify.WEB_URLS);
textView.setLinksClickable(true);

in XML should be

<TextView
    android:id="@+id/txtview"
    android:autoLink="web"
    android:linksClickable="true"
    />

Solution 5 - Html

String data="MyTest";

textView.setText(data);
textView.setText(Html.fromHtml(data));
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setLinksClickable(true);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGunnar LiumView Question on Stackoverflow
Solution 1 - HtmlGunnar LiumView Answer on Stackoverflow
Solution 2 - HtmlCharlie TaboneView Answer on Stackoverflow
Solution 3 - HtmlCayeView Answer on Stackoverflow
Solution 4 - HtmlUmakant PatilView Answer on Stackoverflow
Solution 5 - HtmlM.GanjiView Answer on Stackoverflow