简体   繁体   中英

Load link in WebView Android

WebView webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("http://google.com");

This is my code for webview. It works fine but when a link is clicked it opens the default browser and does not load the link in webview.

Help me out!

You need to implement your own WebViewClient to tell the webView wich urls or domanis should handle. Something like this:

private class BaseWebViewClient extends WebViewClient {

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        if (Uri.parse(request.getUrl().toString()).getHost().contains("yourdomain.com.ar")) {
            callback.setWebView(view);
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
        startActivity(intent);
        return true;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().contains("yourdomain.com.ar")) {
            callback.setWebView(webView);
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
    }

}

Then set it to your webView element:

webView.setWebViewClient(new BaseWebViewClient());
webview.setWebViewClient(new WebViewClient())

in your Activity

WebView webView = (WebView) findViewById(R.id.webView);

webView.setWebViewClient(new BaseWebViewClient());

webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl("http://www.google.com");

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