Some1Else Some1Else - 1 year ago 149
Android Question

Android linkify URLs links non URLs

I want to make web links inside a textview clickable. I used this code

Linkify.addLinks(tv, Linkify.WEB_URLS);

which does linkify the web site URLs but also seems to randomly link other text like dzo.yzw and others.

How can I tell the linkify to only link URLs? To try and detect links starting with http:// or https:// beginnings I tried this pattern compiling

Pattern httpPattern = Pattern.compile("^(http|https)://");
Linkify.addLinks(tv, httpPattern,"");

but that did not work (no links were highlighted). Is that RegEx correct? What should the 3rd parameter to addLinks be?

Thanks for any tips to get this working.

Answer Source

After much searching and trial and error, this is the solution. Do not use the default Linkiny.WEB_URLS. Use a custom regex pattern that looks for links. I used the following (et is an EditText).

Pattern httpPattern = Pattern.compile("[a-z]+:\\/\\/[^ \\n]*");
Linkify.addLinks(et, httpPattern,"");

That will only linkify URLs and not other strings with 2 words separated by a full stop as Linkify.WEB_URLS can do.

If that regex is not good enough for your needs see the following link for heaps of tested alternatives that handle more complex cases

Hope that helps someone else with the same issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download