ListView與GridView非同步載入圖片
<span style="font-size:16px;">package com.xxx.xxx;
import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.URL; import java.util.HashMap;
import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message;
/** * 圖片非同步載入 * */
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache;
public AsyncImageLoader() { imageCache = new HashMap<String, SoftReference<Drawable>>();
}
/** * 載入drawable,讀取到drawable後用hashmap存起來,以圖片地址為key,這樣在重複載入的時候就可以直接取值了
* * @param imageUrl * @param imageCallback * @return drawable */
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
new Thread() {
@Override public void run() {
Drawable drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start(); return null;
}
/** * @param strUrl * @return drawable */
private static Drawable loadImageFromUrl(String strUrl) {
URL url; InputStream i = null;
try { url = new URL(strUrl);
i = (InputStream) url.getContent();
} catch (Exception e) {
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(i, "src");
return d;
}
public interface ImageCallback {
/** 這個介面用來實現回撥 * @param imageDrawable * @param imageUrl */
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}</span>
這個類用到了SoftReference軟引用,在記憶體不足的情況下自動釋放快取,不至於在載入圖片過多的時候產生記憶體洩露。
然後自定義的Adapter的getView方法中這樣載入圖片:
<span style="font-size:16px;"></span>
<span style="font-size:16px;">
Drawable cachedImage = imageLoader.loadDrawable(AppMessageUrl.IMAGEURL + iconUrl, new ImageCallback() {
public void imageLoaded(Drawable imageDrawable, String imageUrl) {
holder.imageView.setImageDrawable(imageDrawable);
}
});
if (cachedImage == null) {
holder.imageView.setImageResource(R.drawable.no_apk); //在圖片沒有讀取出來的情況下預先放一張圖
} else { holder.imageView.setImageDrawable(cachedImage);
}</span>