【发布时间】:2010-07-14 20:08:34
【问题描述】:
我编写了一个简单的 helloworld 应用程序,它带有一个 WebView,它在我的资产文件夹中的 simple.html 页面上有一个指向 CNN 的链接。
<a href="http://cnn.com">cnn.com</a>
如何在我的 Activity 上捕获对此的点击,停止 WebView 导航,然后通知 Activity “http://CNN.com”被点击?
【问题讨论】:
我编写了一个简单的 helloworld 应用程序,它带有一个 WebView,它在我的资产文件夹中的 simple.html 页面上有一个指向 CNN 的链接。
<a href="http://cnn.com">cnn.com</a>
如何在我的 Activity 上捕获对此的点击,停止 WebView 导航,然后通知 Activity “http://CNN.com”被点击?
【问题讨论】:
然后您必须将WebViewClient 设置为您的WebView 并覆盖shouldOverrideUrlLoading 和onLoadResource 方法。举个简单的例子:
WebView yourWebView; // initialize it as always...
// this is the funny part:
yourWebView.setWebViewClient(yourWebClient);
// somewhere on your code...
WebViewClient yourWebClient = new WebViewClient(){
// you tell the webclient you want to catch when a url is about to load
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
return true;
}
// here you execute an action when the URL you want is about to load
@Override
public void onLoadResource(WebView view, String url){
if( url.equals("http://cnn.com") ){
// do whatever you want
}
}
}
【讨论】: