private static class ViewHolder {
ImageView imageView;
TextView region;
TextView area;
TextView id;
TextView shop_name;
public String imageURL;
public Bitmap bitmap;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO
ViewHolder viewHolder = null;
if (arg1 == null) {
arg1 = myInflater.inflate(R.layout.details, arg2, false);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) arg1.findViewById(R.id.imageView1);
viewHolder.region = (TextView) arg1.findViewById(R.id.textView1);
viewHolder.area = (TextView) arg1.findViewById(R.id.textView2);
viewHolder.id = (TextView) arg1.findViewById(R.id.textView3);
viewHolder.shop_name = (TextView) arg1.findViewById(R.id.textView4);
arg1.setTag(viewHolder);
}
viewHolder = (ViewHolder)arg1.getTag();
viewHolder.imageView.setImageResource(R.drawable.loading);
ShopEntry entry = getItem(arg0);
viewHolder.imageURL = entry.image_url;
viewHolder.region.setText(entry.region);
viewHolder.area.setText(entry.area);
viewHolder.id.setText(entry.id);
viewHolder.shop_name.setText(entry.shop_name);
new DownloadAsyncTask().execute(viewHolder);
return arg1;
}
private class DownloadAsyncTask extends AsyncTask<ViewHolder, Void, ViewHolder> {
@Override
protected ViewHolder doInBackground(ViewHolder... params) {
// TODO Auto-generated method stub
//load image directly
ViewHolder viewHolder = params[0];
try {
URL imageURL = new URL(viewHolder.imageURL);
viewHolder.bitmap = BitmapFactory.decodeStream(imageURL.openStream());
} catch (IOException e) {
// TODO: handle exception
Log.e("test", "Downloading Image Failed");
viewHolder.bitmap = null;
}
return viewHolder;
}
@Override
protected void onPostExecute(ViewHolder result) {
// TODO Auto-generated method stub
if (result.bitmap == null) {
result.imageView.setImageResource(R.drawable.loading);
} else {
result.imageView.setImageBitmap(result.bitmap);
}
}
}
在上面的代码中,我在列表视图自定义适配器上实现了异步任务。问题是,当图像重新加载时,它被替换为旧图像,而不是清除旧图像然后重新加载新图像,因此显示顺序不正确。
我已经把
viewHolder.imageView.setImageResource(R.drawable.loading);
在getview()适配器里面,但似乎无法正常工作,如何解决?感谢
答案 0 :(得分:1)
您的异步任务下载图像的时间可能是适配器回收视图持有者,因此异步任务将错误的图像设置为视图持有者实例。
您需要注意异步任务将位图分配给有效的视图持有者而不是已经过时的视图。