本文執行個體講述了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); }
這個是在前面一篇http://www.jb51.net/article/90408.htm基礎上修改的。主要為了加入LruCache
後來發現,這種方法要不停的開闢新的線程,效率並不是很高。最後改為加入一後台線程,不停從後進先出隊列中取出任務進行處理。
更多關於Android相關內容感興趣的讀者可查看本站專題:《Android視圖View技巧總結》、《Android編程之activity操作技巧總結》、《Android操作SQLite資料庫技巧總結》、《Android操作json格式資料技巧總結》、《Android資料庫操作技巧總結》、《Android檔案操作技巧匯總》、《Android編程開發之SD卡操作方法匯總》、《Android開發入門與進階教程》、《Android資源操作技巧匯總》及《Android控制項用法總結》
希望本文所述對大家Android程式設計有所協助。