在Android中将数据加载到webview之前显示加载

时间:2012-12-08 06:42:02

标签: android webview progress-bar

如何在运行此代码时显示加载图像?

HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet("http://www.google.com");
      try
      {
          HttpResponse response = client.execute(request);
          BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
          String line;
          StringBuilder str = new StringBuilder();
          while((line = reader.readLine()) != null) {
              str.append(line);
      }
          objwebview.loadData(str.toString(), "text/html", "UTF-8");
  }
  catch(Exception e)
  {
      e.printStackTrace();
      objwebview.loadData(e.toString(), "text/html", "UTF-8");
  }

1 个答案:

答案 0 :(得分:3)

使用AsyncTask

更改代码,以显示加载栏
private class Getdataasynktask extends AsyncTask<String, Void, String> {

ProgressDialog progressDialog = new ProgressDialog(context);

      @Override
      protected void onPostExecute(String result) {     
      // show loaging bar here

    progressDialog.setMessage("Loading...");
    progressDialog.setCancelable(false);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setProgress(0); // set percentage completed to 0%
    progressDialog.show();

      }

      @Override
      protected String doInBackground(String... params) {
          String strdata= getdatafromserver();
            return strdata;
      }      

      @Override
      protected void onPreExecute(String result) {

       objwebview.loadData(result.toString(), "text/html", "UTF-8");
       // dismiss progress bar here
       progressDialog.dismiss();
      }
 public String getdatafromserver(){
     String line;
      objwebview.loadData(str.toString(), "text/html", "UTF-8");
      HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet("http://www.google.com");
      try
      {
          HttpResponse response = client.execute(request);
          BufferedReader reader = new BufferedReader(new 
                    InputStreamReader(response.getEntity().getContent()));

          StringBuilder str = new StringBuilder();
          while((line = reader.readLine()) != null) {
              str.append(line);
      }

  }
  catch(Exception e)
  {
      e.printStackTrace();
      line=e.toString();

  }
return line;
}
}

从UI Thread使用

执行此AsyncTask
new Getdataasynktask().execute("");

您还可以使用onProgressUpdatepublishProgress使用AsyncTask显示加载栏并将结果发布到Ui线程。有关更多信息,请参阅

http://developer.android.com/reference/android/os/AsyncTask.html