classBitmapDownloaderTaskextendsAsyncTask<String,Void,Bitmap>{privateStringurl;privatefinalWeakReference<ImageView>imageViewReference;publicBitmapDownloaderTask(ImageViewimageView){imageViewReference=newWeakReference<ImageView>(imageView);}@Override// Actual download method, run in the task threadprotectedBitmapdoInBackground(String...params){// params comes from the execute() call: params[0] is the url.returndownloadBitmap(params[0]);}@Override// Once the image is downloaded, associates it to the imageViewprotectedvoidonPostExecute(Bitmapbitmap){if(isCancelled()){bitmap=null;}if(imageViewReference!=null){ImageViewimageView=imageViewReference.get();if(imageView!=null){BitmapDownloaderTaskbitmapDownloaderTask=getBitmapDownloaderTask(imageView);// Change bitmap only if this process is still associated with this ImageViewif(this==bitmapDownloaderTask){imageView.setImageBitmap(bitmap);}}}}}
对于ListView上的图像浏览,当用户快速滑动ListView时,某一个ImageView对象会被用到很多次,每一次显示都会触发一个下载,然后改变对应的图片。和大多数并行应用一样,有顺序相关的问题。在这个程序中,不能保证下载会按开始的顺序结束,有可能先开始的后下载完,,“ The result is that the image finally displayed in the list may come from a previous item, which simply happened to have
taken longer to download. ” 结果就是,由于与该item对应的网络图片下载慢,导致该item位置还暂时显示着之前的item显示的图片(还没被刷新,有可能长时间不被刷新)为了解决这个问题,我们应该记住下载的顺序,使得最后的下载会被有效地显示,要让每一个ImageView记住它们的上一次下载任务。因此我们给出了DownloadedDrawable类,向ImageView中加入对对应下载任务的弱引用来暂时绑定正在下载图片的ImageView。
static class DownloadedDrawable extends ColorDrawable ;//该类包含了一个对下载的弱引用