在WebView显示后关闭ProgressDialog

时间:2015-04-15 12:43:57

标签: android webview

如何在加载WebView时使用ProgressDialog等待?

有时myText有大量文本,有些旧设备无法快速加载WebView。我想在加载WebView时显示ProgressDialog,当它已经显示时我想要关闭ProgressDialog。

我有:

ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Please wait...");
dialog.setIndeterminate(true) ;
dialog.show();

String myText = "some text";
WebView myWebView = (WebView)findViewById(R.id.webView);
myWebView.loadDataWithBaseURL("", myText, "text/html", "UTF-8", "");

dialog.dismiss();

它没有显示任何ProgressDialog。

如果我不使用dismiss,我总会看到我的ProgressDialog。

3 个答案:

答案 0 :(得分:1)

使用AsyncTask

 // ..onCreate code come here...


 Button button = (Button) findViewById(R.id.button);
     bt.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
            // TODO Auto-generated method stub
               new LongOperation().execute(); // here calling LongOperation class to do `AsyncTask`.
            }

        });

 private class LongOperation extends AsyncTask<Void, Void, Void> {
    ProgressDialog dialog; 

     @Override
    protected void onPreExecute() {

     dialog = new ProgressDialog(MainActivity.class);
     dialog.setTitle("Please wait...");
     dialog.setIndeterminate(true) ;
     dialog.show();
     }

    @Override
    protected String doInBackground(Void... params) {

     // background operation comes here..

    }

    @Override
    protected void onPostExecute(String result) {

       // close progressDialog here by calling
         dialog.dismiss();
    }
 }

答案 1 :(得分:0)

将此代码放在包含Web视图的当前Java类中。

  private class MyWebViewClient extends WebViewClient {

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        if(dialog.isShowing() && dialog != null) {

            dialog.dismiss();
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {

        super.onPageStarted(view, url, favicon);


        if(!dialog.isShowing() && dialog != null) {

            dialog.show();
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        return super.shouldOverrideUrlLoading(view, url);
    }


}

并设置此

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.setWebViewClient(new MyWebViewClient());

下面你初始化了你的网页浏览

答案 2 :(得分:0)

试试吧,

webView.setWebViewClient(new WebViewClient()
    {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            progDailog.show();
            view.loadUrl(url);

            return true;
        }

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