Android动态加载图片时显示进度条

时间:2013-07-24 09:28:27

标签: android android-layout android-listview android-asynctask

在我的一个项目中,我正在从动态网址加载图片。现在我需要显示所有图像加载的加载对话框。我正在使用Async任务加载图像。 我是android的新手。请任何人给我一点帮助

我的代码看起来像。

TableLayout table = (TableLayout)findViewById(R.id.tableLayout_1);
        for(Integer i=0;i<2;i++){


            TableRow rowP = new TableRow(this);
            rowP.setBackgroundColor(Color.parseColor("#FFF000"));




            ImageView image = new ImageView(this);
            String ed="http://www.domain.com/image.jpg";
            image.setTag(ed);
            DownloadImagesTask td=new DownloadImagesTask();
            td.execute(image);

            rowP.addView(image);
            table.addView(rowP);
            }
        }


private class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

    ImageView imageView = null;

    @Override
    protected Bitmap doInBackground(ImageView... imageViews) {
        this.imageView = imageViews[0];
        return download_Image((String)imageView.getTag());
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }

    private Bitmap download_Image(String url) {

        Bitmap bmp =null;
        try{
            URL ulrn = new URL(url);
            HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
            InputStream is = con.getInputStream();
            bmp = BitmapFactory.decodeStream(is);
            if (null != bmp)
                return bmp;

            }catch(Exception e){}
        return bmp;
    }
}

提前致谢

修改

private class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

        ImageView imageView = null;
        ProgressDialog dialog;
        Context context;

        public DownloadImagesTask(Context context) {
            this.context = context;
        }

        @Override
        protected Bitmap doInBackground(ImageView... imageViews) {
            this.imageView = imageViews[0];
            return download_Image((String)imageView.getTag());
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
            if (dialog != null)
                dialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = ProgressDialog.show(context, "Title","Message");
        }

        private Bitmap download_Image(String url) {

            Bitmap bmp =null;
            try{
                URL ulrn = new URL(url);
                HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
                InputStream is = con.getInputStream();
                bmp = BitmapFactory.decodeStream(is);
                if (null != bmp)
                    return bmp;

                }catch(Exception e){}
            return bmp;
        }
    }

4 个答案:

答案 0 :(得分:4)

DownloadImageTask

中添加以下行
@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = ProgressDialog.show(context, "Title",
                "Message");
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    if (dialog != null)
        dialog.dismiss();
    //rest of the code
}

并在ProgressDialog dialog中声明DownloadImageTask

要传递Context,您需要为此创建一个构造函数。

private class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

    ImageView imageView = null;
    ProgressDialog dialog;
    Context context;

    public DownloadImagesTask(Context context) {
        this.context = context;
    }
    //... rest of code ....
}

答案 1 :(得分:4)

如果你想保持它简单/清晰/快速和漂亮,你不应该自己下载,特别是如果你是Android新手。

只需使用开源库:

最简单的是 http://square.github.io/picasso/

另一个更复杂的问题:https://github.com/nostra13/Android-Universal-Image-Loader

答案 2 :(得分:2)

如果要在进度条上显示进度,可以使用此代码。它就像一个魅力。

这里dwBar是进度条。 imView是你想要显示图片的imageView。

private class DownloadImageTask extends AsyncTask<String, String, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dwBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {

                int increment;
                byte[] data;
                InputStream in = null;
                int response;
                URL url = new URL(params[0]);
                URLConnection conn = url.openConnection();
                if (!(conn instanceof HttpURLConnection))
                    throw new IOException("Not an HTTP connection");
                try {
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setInstanceFollowRedirects(true);
                    httpConn.setRequestMethod("GET");
                    httpConn.connect();

                    response = httpConn.getResponseCode();
                    if (response == HttpURLConnection.HTTP_OK) {
                        in = httpConn.getInputStream();
                    }
                    int length = httpConn.getContentLength();

                    data = new byte[length];
                    increment = length / 100;
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                    int count = -1;
                    int progress = 0;

                    while ((count = in.read(data, 0, increment)) != -1) {
                        progress += count;
                        publishProgress("" + (int) ((progress * 100) / length));
                        outStream.write(data, 0, count);
                    }
                    bitmap = BitmapFactory.decodeByteArray(
                            outStream.toByteArray(), 0, data.length);
                    in.close();
                    outStream.close();

                } catch (Exception ex) {
                    Log.d("Networking", ex.getLocalizedMessage());
                    throw new IOException("Error connecting");
                }

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return bitmap;
        }

        protected void onProgressUpdate(String... progress) {
            dwBar.setProgress(Integer.parseInt(progress[0]));
        }

        protected void onPostExecute(Bitmap bm) {

            dwBar.setVisibility(View.GONE);

            if (bm != null) {
                imView.setImageBitmap(bm);
            }
        }
    }

答案 3 :(得分:0)

以下是在屏幕上下载和显示图像的完整domanstration of actvity。

这是Activity的xml文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Download Button -->
    <Button android:id="@+id/btnProgressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download File with Progress Bar"
        android:layout_marginTop="50dip"/>

    <!-- Image view to show image after downloading -->
    <ImageView android:id="@+id/my_image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

这是活动代码。

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidDownloadFileByProgressBarActivity extends Activity {

  // button to show progress dialog
  Button btnShowProgress;

  // Progress Dialog
  private ProgressDialog pDialog;
  ImageView my_image;
  // Progress dialog type (0 - for Horizontal progress bar)
  public static final int progress_bar_type = 0;

  // File url to download
  private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_android_download_file_by_progress_bar);

    // show progress bar button
    btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
    // Image view to show image after downloading
    my_image = (ImageView) findViewById(R.id.my_image);
    /**
     * Show Progress bar click event
     * */
    btnShowProgress.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        // starting new Async Task
        new DownloadFileFromURL().execute(file_url);
      }
    });
  }

  /**
   * Showing Dialog
   * */
  @SuppressWarnings("deprecation")
  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type: // we set this to 0
      pDialog = new ProgressDialog(this);
      pDialog.setMessage("Downloading file. Please wait...");
      pDialog.setIndeterminate(false);
      pDialog.setMax(100);
      pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
      pDialog.setButton("Cancel", (DialogInterface.OnClickListener) null);
      pDialog.setCancelable(true);
      pDialog.show();
      return pDialog;
    default:
      return null;
    }
  }

  /**
   * Background Async Task to download file
   * */
  class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
      showDialog(progress_bar_type);
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
      int count;
      try {
        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();
        // this will be useful so that you can show a tipical 0-100% progress
        // bar
        int lenghtOfFile = conection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream
        OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
          total += count;
          // publishing the progress....
          // After this onProgressUpdate will be called
          publishProgress("" + (int) ((total * 100) / lenghtOfFile));

          // writing data to file
          output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();

      } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
      }

      return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
      // setting progress percentage
      pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
      // dismiss the dialog after the file was downloaded
      dismissDialog(progress_bar_type);

      // Displaying downloaded image into image view
      // Reading image path from sdcard
      String imagePath = Environment.getExternalStorageDirectory().toString()
          + "/downloadedfile.jpg";
      // setting downloaded into image view
      my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    }

  }
}

只需使用以下xml文件添加此活动。