2

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

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");
  }
4

1 回答 1

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 线程执行此 AsyncTask 使用

new Getdataasynktask().execute("");

并且您还可以使用onProgressUpdateandpublishProgress来显示加载栏,使用AsyncTask并将结果发布到 Ui 线程。欲了解更多信息,请参阅

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

于 2012-12-08T06:51:33.447 回答