Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This seems like a trivial problem, but is 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?

like image 772
Gunnar Lium Avatar asked Nov 29 '10 11:11

Gunnar Lium


People also ask

Is TextView clickable android?

Just like Buttons and ImageViews we can add onClickListeners to TextViews by simply adding the attribute android:onClick="myMethod" to your TextView XML tag. The other way, TextView tv = (TextView) this.

What is autoLink in android?

andorid:autoLink => By using this attribute, android can controls whether links(such as urls, emails, phone and address) are automatically found and converted to clickable links.

How do I use Linkify?

To call linkify in android, we have to call linkify. addLinks(), in that method we have to pass textview and LinkifyMask. Linkify. WEB_URLS: It going make URL as web url, when user click on it, it going to send url to default web browsers.


2 Answers

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.

like image 111
Gunnar Lium Avatar answered Sep 24 '22 08:09

Gunnar Lium


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.

like image 37
Charlie Tabone Avatar answered Sep 25 '22 08:09

Charlie Tabone