Android: How to check for successful load of url when using webview.loadUrl

后端 未结 4 1892
旧巷少年郎
旧巷少年郎 2020-12-16 16:25

In webview android I am trying to load a url and in order to check if the load of this url is done successfully (internet connection was available, the server was up etc) I

4条回答
  •  攒了一身酷
    2020-12-16 16:45

    Here is what I came up with, it works like a charm.

        Boolean failedLoading = false;
        WebView webView = view.findViewById(R.id.webView);
        webView.loadUrl("www.example.com");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!failedLoading) {
                    webView.setVisibility(View.VISIBLE);
                    webView.setAlpha(0f);
                    ObjectAnimator anim  = ObjectAnimator.ofFloat(webView, "alpha",1f);
                    anim.setDuration(500);
                    anim.start();
                }
            }
    
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                failedLoading = true;
            }
        });
    

    It will also work great if you add some kind of a refresh button and then you can call the code above inside a function to try again.

提交回复
热议问题