8

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

我的 webView 最初是在 main.xml 中使用 android:visibility="gone" 隐藏的,我使用 myWebView.setVisibility(1) 将其动态更改为可见;当页面完全加载时(并且它可以工作)。现在,我想在检测到错误时隐藏这个 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.
            //  }
    }

有任何想法吗?

4

2 回答 2

6

这是我的想法:

 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;
        }
    });
于 2017-04-07T04:16:31.500 回答
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;
        }
    }
}
于 2019-01-17T11:53:33.163 回答