Android WebView打开链接

时间:2017-09-26 04:10:17

标签: java android android-webview

我在Android Studio编写Android应用程序,我有一个带有WebView的Activity,想知道是否有办法检测用户在WebView中点击的超链接

我希望能够检测到链接是否 link1.com 它会继续正常打开但是如果 link2.com 它会取消并打开其他活动

3 个答案:

答案 0 :(得分:2)

使用此选项检查网址并执行任务

private class MyWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if(url.equals(link2)){
            Intent i = new Intent (Youractivityname.this, SecondActivity.class);
            startactivity(i);
        }

        return true;
    }

}

答案 1 :(得分:2)

按照Faizal Abbas的回答。创建一个扩展WebViewClient的类,重写方法shouldOverrideUrlLoading(),然后将WebViewClient设置为webview。

WebView webView = yourWevView; webView.setWebViewClient(new MyWebViewClient());

答案 2 :(得分:0)

对于您所需要的,您必须使用WebViewClient,如下所示:

WebView webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if(url.contains("link2.com")){//if url contains link2.com open new activity
            startactivity(new Intent(CurrentActivity.this, SecondActivity.class)); //replace CurrentActivity with the activity where you are writing this code and SecondActivty with the activity you want to open
        }

        else {
            //do nothing, webview will load that link
        }

        return true;
    }    

});