正如标题所说,我有这个问题。
因为我需要从网络中检索图像,所以我已经实现了一个解释here
我将发布Adapter和ImageDownloader代码(我已经自由修改了下载程序,以使该功能更适合我的程序)。
适配器方法:
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.grid_adapter_camera_layout, parent, false);
holder = new ViewHolder();
holder.progress = (ProgressBar) view.findViewById(R.id.progressBar);
holder.image = (ImageView) view.findViewById(R.id.camera_image);
holder.text = (TextView) view.findViewById(R.id.camera_name);
holder.text.setEllipsize(TextUtils.TruncateAt.END);
holder.text.setLines(2);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
imgDownloader.download(values.get(position).getUrl(), holder.image, holder.progress);
}
这里是ImageDownloader(我发布了代码中最合适的部分,如果你还需要进一步的请求它)。
public void download(String url, ImageView imageView, ProgressBar progress) {
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap != null) {
cancelPotentialDownload(url, imageView);
imageView.setImageBitmap(bitmap);
} else if(cancelPotentialDownload(url, imageView)){
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView, progress);
imageView.setTag(new WeakReference<BitmapDownloaderTask>(task));
task.execute(url);
}
}
private boolean cancelPotentialDownload(String url, ImageView imageView) {
BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
if (bitmapDownloaderTask != null) {
String bitmapUrl = bitmapDownloaderTask.url;
if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) {
bitmapDownloaderTask.cancel(true);
} else {
// The same URL is already being downloaded.
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
private BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) {
if (imageView != null && imageView.getTag() != null) {
return ((WeakReference<BitmapDownloaderTask>) imageView.getTag()).get();
}
return null;
}
public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
String url;
WeakReference<ImageView> viewReference;
WeakReference<ProgressBar> progressReference;
public BitmapDownloaderTask(ImageView view, ProgressBar progress) {
view.setTag(false);
viewReference = new WeakReference<ImageView>(view);
progressReference = new WeakReference<ProgressBar>(progress);
}
@Override
protected Bitmap doInBackground(String... params) {
url=params[0];
Log.e("DOWNLOAD URL", url);
return downloadBitmap(params[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
if (isCancelled())
result = null;
addBitmapToCache(url, result);
if (viewReference != null) {
ImageView imgView = viewReference.get();
BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imgView);
if (this == bitmapDownloaderTask) {
if (result != null)
imgView.setImageBitmap(result);
else
imgView.setImageResource(R.drawable.no_signal);
}
}
if (progressReference != null) {
ProgressBar prog = progressReference.get();
if (prog != null)
prog.setVisibility(View.GONE);
}
}
}