Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to have WebView auto-link URLs and phone numbers in Android?

If a page has a URL or a phone number on it that isn't a link is there any way to have WebView recognize it and automatically turn it into a link like you can with TextViews?

With a TextView you would simply set the android:autoLink to the desired settings:

<TextView
    android:autoLink="web|phone"
    ... />

but I can't find any equivalent for WebView.

like image 998
Jeremy Logan Avatar asked Nov 16 '09 18:11

Jeremy Logan


2 Answers

If you are loading your own (web) content from a String, then you can do something like this:

final String content = "My email is: [email protected] ...";
Spannable sp = new SpannableString(content);
Linkify.addLinks(sp, Linkify.ALL);
final String html = "<body>" + Html.toHtml(sp) + "</body>";
myWebView.loadData(html, "text/html", "utf-8");
like image 141
Harri Avatar answered Oct 18 '22 20:10

Harri


I don't know about any way which would make this work just by changing a setting, but a workaround would be to wait until the web page finishes loading and then do:

yourWebView.loadUrl("javascript:(function(){ /* code that creates links */ })()");

This will inject javaScript into the already loaded web page. There's a slightly longer example available here: http://lexandera.com/2009/01/injecting-javascript-into-a-webview/.

You can find the JavaScript source for creating links if you take a look at the source of Linkify script for Greasemonkey (it's a plugin for Firefox in case you're not familiar with it). I believe it comes with the default install.

like image 32
Aleksander Kmetec Avatar answered Oct 18 '22 21:10

Aleksander Kmetec