效果图如上:
异步加载的核心类:
AsyncImageLoader
package cn.wangmeng.test;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
/**
* 异步加载图片类
*@author hsx
*@date 2012-11-21
*@Description
*/
public class AsyncImageLoader {
/**
* SoftReference的语义就是当内存不够用的时候,GC会回收SoftReference所引用的对象。
* 所以,在memory sensitive的程序中将某些大型数据设置成SoftReference再合适不过了。
*/
private HashMap<String, SoftReference<Drawable>> imageCache;
/**
* 该类的构造方法
*/
public AsyncImageLoader()
{
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
/**
*
*@author hsx
*@Description 获得Drawable的对象
*@param imageUrl
*@param imageCallback
*@return
*
*/
public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback)
{
/**
* 调用该方法后,先执行此句,如果imageCache中有imageUrl这个key则,取出对应的drawable对象
*/
if (imageCache.containsKey(imageUrl))
{
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
/**
* 获得软引用中的Drawable对象
*/
Drawable drawable = softReference.get();
if (drawable != null)
{
return drawable;
}
}
/**
* 否则执行线程操作
*/
final Handler handler = new Handler()
{
public void handleMessage(Message message)
{
/**
* 此处调用imageLoaded方法已经在adapter中重写的方法 了,将获取到的Drawable对象赋给该方法
*/
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;
}
public static Drawable loadImageFromUrl(String url)
{
URL m;
InputStream i = null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(i, "src");
return d;
}
/**
* 接口中有个方法imageLoaded
*@author hsx
*@date 2012-11-21
*@Description
*/
public interface ImageCallback
{
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}
源码未完,请点击链接下载完整源码
源码下载地址:http://download.youkuaiyun.com/detail/abc13939746593/4817333