WebView 加载后关闭 ProgressDialog url 不起作用

Dismiss ProgressDialog after WebView loads url does not work

我创建了一个 webview,当页面加载时,会有一个 ProgressDialog。好吧,直到这一点一切正常。 但现在我希望 ProgressDialog 在加载 url 后被关闭。 这行不通。

我的代码:

private WebView webViewNews;
private ProgressDialog progressDialogWebViewNews;

  webViewNews = (WebView) findViewById(R.id.webViewNews);
  WebSettings webSettings = webViewNews.getSettings();
  webSettings.setJavaScriptEnabled(true);
  webViewNews.setWebViewClient(new WebViewClient() {
      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          progressDialogWebViewNews = new ProgressDialog(MainActivity.this);
          progressDialogWebViewNews.setCancelable(false);
          progressDialogWebViewNews.setTitle("Demo...");
          progressDialogWebViewNews.setMessage("Demo");
          progressDialogWebViewNews.show();
      }

      @Override
      public void onPageFinished(WebView view, String url) {
          progressDialogWebViewNews.dismiss();
          super.onPageFinished(view, url);
      }
  });
  webViewNews.loadUrl("http://www.demo.com");

也许您应该创建一个简单的 WebView 对象:

    WebView webView = (WebView) getActivity().findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("yourURL");
    final ProgressDialog progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Loading...");
    progressDialog.show();
    progressDialog.setCancelable(false);
    webView.setWebViewClient(new WebViewClient()
    {

        public void onPageFinished(WebView view, String url)
        {
            progressDialog.dismiss();
        }
    });

对我有用。

当您将变量传递给匿名 class 时,该变量会自动变为 final,从而阻止其更改。尝试将进度对话框作为内部客户端 class 的成员。这也是一个更好的设计,使您的代码更易于维护。

class MyClient extends WebViewClient() {
      private ProgressDialog progressDialogWebViewNews;

      public MyClient(Context c){
             progressDialogWebViewNews = new ProgressDialog(c);
      }

      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          progressDialogWebViewNews.setCancelable(false);
          progressDialogWebViewNews.setTitle("Demo...");
          progressDialogWebViewNews.setMessage("Demo");
          progressDialogWebViewNews.show();
      }

      @Override
      public void onPageFinished(WebView view, String url) {
          progressDialogWebViewNews.dismiss();
          super.onPageFinished(view, url);
      }
}

webViewNews.setWebViewClient(new MyClient(MainActivity.this)); 

删除 super.onPageFinished(view, url),然后在回调方法中关闭它之前先检查进度对话框是否显示。

If (progressDialogWebViewNews.showing){
progressDialogWebViewNews.dismiss();
}