原理很简单,主要是用到了回调方法,下面是异步加载图片的类
<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>