如何隐藏WebView错误页面。可能吗?

时间:2013-01-25 10:29:51

标签: android error-handling webview

我搜索并发现了类似的问题,但他们主要说的是如何更改webView内容,而不是如何隐藏它。

我的webView最初是在main.xml中使用android:visibility =“gone”隐藏的,我使用myWebView.setVisibility(1)将其改为din可见;当页面完全加载(并且它工作)。现在,我想在检测到错误时隐藏此webView。我想隐藏它的原因是因为我在布局中有一个很好的背景,可以告知错误。我知道这不是最好的方法,可能会在以后更改它,但现在,我想解决的是为什么webView在发生错误时没有隐藏(只是为了好玩,或许)。

这是我尝试过的:

@Override
public void onReceivedError (WebView view, int errorCode, 
                             String description, String failingUrl) {

        myWebView = (WebView) findViewById(R.id.webview);  
        // myWebView.setVisibility(0); // Doesn't work!

        // if (errorCode == ERROR_TIMEOUT) { // Commented just for trying

        try {view.stopLoading();} catch(Exception e){}
        try {view.clearView();} catch(Exception e){}

            view.loadUrl("file:///android_asset/error.html"); // This Works but I don't want it this way.
            view.setBackgroundColor(0x00000000); // Trying to make it transparent. Doesn't work here
            view.setVisibility(View.GONE); // Doesn't work. I have tried also with myWebView.
            //  }
    }

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

这是我的想法:

 boolean isPageError = false;

 webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
           isPageError = false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isPageError){
                webview.setVisibility(View.GONE);
                txtError.setVisibility(View.VISIBLE);
                txtError.setText("error message");
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
           isPageError = true;
        }
    });

答案 1 :(得分:0)

  

对我有用

private boolean isError = false;

webView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {
        Log.e(TAG, "onPageFinished");
        if (isError) {
            //Show error
        } else {
            //Hide error
        }
    }

    @Override
    public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
        super.onReceivedError(webView, errorCode, description, failingUrl);
        Log.e(TAG, "onReceivedError Old = " + errorCode);
        if (errorCode == -2) {
            isError = true;
        }
    }

    @Override
    @TargetApi(Build.VERSION_CODES.M)
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        Log.e(TAG, "onReceivedError New = " + error.getErrorCode());
        if (error.getErrorCode() == -2) {
            isError = true;
        }
    }
}