在Android上下载并显示来自URL阵列的图像到多个不同的ImageViews



我有这个代码可以从URL下载照片并在Android上的ImageView中显示。

如果我有一个ArrayList或多个Url的数组要下载并显示在不同的ImageView上,我不知道如何循环。我将感谢任何关于如何进行的帮助或见解!非常感谢。

public class DisplayPhotoTask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;     
    }
    //sets bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) {
        ImageView imageView1 = (ImageView) findViewById(R.id.imageView);
        imageView1.setImageBitmap(result);
    }
    //creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;
        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }
    //makes httpurlconnection and returns inputstream
    private InputStream getHttpConnection(String urlString) throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();
        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();
            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}

例如,您可以使AsyncTask的结果作为List ant编写类似的内容

protected Bitmap doInBackground(String... urls) {
    List<Bitmap> bitmaps = new ArrayList<Bitmap>;
    for (String url : urls) {
        bitmaps.add(downloadImage(url));
    }
    return bitmaps;     
}
protected void onPostExecute(List<Bitmap> result) {
    //...
}

但我真正建议你使用谷歌编写的Volley库,它有非常简单和强大的API(这里是关于它的谷歌I/O会话https://developers.google.com/live/shows/474338138和存储库https://android.googlesource.com/platform/frameworks/volley/)

最新更新