本文实例讲述了Android实现ListView异步加载的方法。分享给大家供大家参考,具体如下:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
…………
ViewHolder VH = null;
…………
VH.mImageView.setTag(position);
VH.mThumb.setImageDrawable(imageLoader.loadDrawable(position,
new ImageCallback() {
public void imageLoaded(Drawable imageDrawable, int position) {
ImageView imageViewByTag = (ImageView) mList.findViewWithTag(position);
if (imageViewByTag != null) {
imageViewByTag.setImageDrawable(imageDrawable);
}
}
}));
}
private static LruCache mCache = new LruCache(100);
public class AsyncImageLoader {
public Drawable loadDrawable(final int position, final ImageCallback callback){
Drawable d = null;
d = mCache.get(position);
if (d == null) {
final Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
callback.imageLoaded((Drawable) msg.obj, position);
}
};
Thread t = new Thread(){
public void run() {
Drawable drawable = Utils.getDrawable(mContext, position, 1, mMyDefaultIcon);
Drawable value = mCache.get(position);//cache有可能已经被更改了,所以重新取一次
if (value == null) {
mCache.put(position, drawable);
} else {
drawable = value;
}
handler.sendMessage(handler.obtainMessage(0,drawable));
};
};
t.setPriority(Thread.MIN_PRIORITY);
t.start();
return mMyDefaultIcon;
} else {
return d;
}
}
}
public interface ImageCallback{
public void imageLoaded(Drawable imageDrawable, int position);
}
后来发现,这种方法要不停的开辟新的线程,效率并不是很高。最后改为加入一后台线程,不停从后进先出队列中取出任务进行处理。
希望本文所述对大家Android程序设计有所帮助。