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

◇◆丶佛笑我妖孽 提交于 2019-12-17 12:30:32

问题


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.


回答1:


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.




回答2:


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

final String content = "My email is: firstname@email.com ...";
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");


来源:https://stackoverflow.com/questions/1744091/is-there-any-way-to-have-webview-auto-link-urls-and-phone-numbers-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!