LruCash使用showImageByThread有Bug
1.剛載入時,可見項目除了最後一個有載入圖片(有時還錯位),其它只顯示ic_launcher
2.要滾動畫面好幾次才會全部載入對應的圖片
程式碼如下
ImageLoader.java
ImageView imageView; String url; LruCache<String, Bitmap> bitmapLruCache; public ImageLoader() { int maxMemory = (int) Runtime.getRuntime().maxMemory(); int cashSize = maxMemory / 4; bitmapLruCache = new LruCache<String, Bitmap>(cashSize) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); } }; } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (imageView.getTag().equals(url)) { imageView.setImageBitmap((Bitmap) msg.obj); } } }; public void showImageByThread(ImageView imageView, final String url) { this.imageView = imageView; this.url = url; Bitmap bitmap = getBitmapFromCash(url); //緩衝沒有bitmap,從網路下載 if (bitmap == null) { new Thread() { @Override public void run() { Bitmap bitmap = getBitmapFromURL(url); //將下載的bitmap存到緩衝 addBitmapToCash(url, bitmap); Message msg = Message.obtain(); msg.obj = bitmap; handler.sendMessage(msg); } }.start(); } else { imageView.setImageBitmap(bitmap); } } public Bitmap getBitmapFromURL(String url) { Bitmap bitmap = null; try { URLConnection connection = new URL(url).openConnection(); InputStream is = connection.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } public void addBitmapToCash(String url, Bitmap bitmap) { if (bitmap != null) { bitmapLruCache.put(url, bitmap); } } public Bitmap getBitmapFromCash(String url) { return bitmapLruCache.get(url); }