标签:
/** * Using Thread * @param imageView * @param url */ public void showImageByThread(final ImageView imageView, final String url) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { Bitmap bitmap = (Bitmap) msg.obj; imageView.setImageBitmap(bitmap); } }; new Thread() { @Override public void run() { Bitmap bitmap = getBitmapFromUrl(url); Message message = Message.obtain(); message.obj = bitmap; mHandler.sendMessage(message); } }.start(); }
public View getView(int position, View convertView, ViewGroup parent)
当它再显示的时候,又一次再写上正确的数据就好了。
可是异步就不一样了,就拿我们这里下载图片来说,每一个图片都有自己的脾气。大家下载的速度都是不一样的,当初始显示ListView时。Item1的图片下载太慢,当你滑上去,显示Item11了,Item11的图显示的飞起,立即就下好了。OK,Item11的图显示好了,可立即。Item1下的慢的图也下好了,它去找Item1,可是它不知道这个时候的Item1已经变成Item11了。它还去给人家设置图像。这不就乱了吗?
所以,我们须要建立一个标志,来让冬眠的朋友回来看看清楚,如今的这个大爷是不是你曾经的那个大爷。
/** * Using Thread * @param imageView * @param url */ public void showImageByThread(final ImageView imageView, final String url) { mHandler = new Handler() { @Override public void handleMessage(Message msg) { ImgHolder holder = (ImgHolder) msg.obj; if (holder.imageView.getTag().equals(holder.url)) { holder.imageView.setImageBitmap(holder.bitmap); } } }; new Thread() { @Override public void run() { Bitmap bitmap = getBitmapFromUrl(url); Message message = Message.obtain(); message.obj = new ImgHolder(imageView, bitmap, url); mHandler.sendMessage(message); } }.start(); }
private class ImgHolder { public Bitmap bitmap; public ImageView imageView; public String url; public ImgHolder(ImageView iv, Bitmap bm,String url) { this.imageView = iv; this.bitmap = bm; this.url = url; } }
这里就利用到了我们在Android异步载入全解析之开篇瞎扯淡里面所提到的:
viewHolder.imageView.setTag(url);
@Override public View getView(int position, View convertView, ViewGroup parent) { String url = mData.get(position); ViewHolder viewHolder = null; if (convertView == null) { viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.listview_item, null); viewHolder.imageView = (ImageView) convertView.findViewById(R.id.iv_lv_item); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.imageView.setTag(url); viewHolder.imageView.setImageResource(R.drawable.ic_launcher); mImageLoader.showImageByThread(viewHolder.imageView, url); return convertView; }
标签:
原文地址:http://www.cnblogs.com/lcchuguo/p/5153868.html