简体   繁体   English

在 WebView Android 中加载链接

[英]Load link in WebView Android

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

This is my code for webview.这是我的 webview 代码。 It works fine but when a link is clicked it opens the default browser and does not load the link in webview.它工作正常,但当点击链接时,它会打开默认浏览器,并且不会在 webview 中加载链接。

Help me out!帮帮我!

You need to implement your own WebViewClient to tell the webView wich urls or domanis should handle.您需要实现自己的 WebViewClient 来告诉 webView 应该处理的 urls 或 domanis。 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 元素:

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

in your Activity在您的Activity

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

webView.setWebViewClient(new BaseWebViewClient());

webView.getSettings().setJavaScriptEnabled(true);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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