本文實例講述了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<Long, Drawable> mCache = new LruCache<Long, Drawable>(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); }這個是在前面一篇//m.survivalescaperooms.com/article/90408.htm基礎上修改的。主要為了加入LruCache
后來發現,這種方法要不停的開辟新的線程,效率并不是很高。最后改為加入一后臺線程,不停從后進先出隊列中取出任務進行處理。
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android視圖View技巧總結》、《Android編程之activity操作技巧總結》、《Android操作SQLite數據庫技巧總結》、《Android操作json格式數據技巧總結》、《Android數據庫操作技巧總結》、《Android文件操作技巧匯總》、《Android編程開發之SD卡操作方法匯總》、《Android開發入門與進階教程》、《Android資源操作技巧匯總》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答