我已经写了一个简单的HelloWorld应用程序,其中包含一个链接到CNN的WebView,并在我的资产文件夹中的simple.html页面上展示。
<a href="http://cnn.com">cnn.com</a>
我该如何在我的Activity中捕获此处的点击事件,停止WebView的导航,并通知Activity "http://CNN.com"被点击了?
我已经写了一个简单的HelloWorld应用程序,其中包含一个链接到CNN的WebView,并在我的资产文件夹中的simple.html页面上展示。
<a href="http://cnn.com">cnn.com</a>
我该如何在我的Activity中捕获此处的点击事件,停止WebView的导航,并通知Activity "http://CNN.com"被点击了?
然后你需要为你的WebView
设置一个WebViewClient
,并重写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
}
}
}