简体   繁体   中英

Android WebView opening link

I am coding an Android app in Android Studio, I have an Activity with a WebView and would like to know if there is a way to detect a hyperlink a user clicks in the WebView

I want to be able to detect if the link is link1.com it will continue and open like normal but if its link2.com it cancels and opens another activity

Use this to Check the url and perform your task

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;
    }

}

do as answered by Faizal Abbas.Create a class extending WebViewClient,override the method shouldOverrideUrlLoading(),then set the WebViewClient to your webview.

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

For what you need, you have to use a WebViewClient like this:

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;
    }    

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM