实现异步加载图片
2013-12-02 17:34
351 查看
项目中会经常用到异步加载图片并保存到SoftReference中,特此整理一下。
调用处的使用方法如下:
/** * 异步加载图片,使用SoftReference 软引用 * 它的作用是管理内存,防止内存溢出,还可以缓冲一些drawable让我们直接使用,当内存不足时才自动回收这些引用对象 * * @author Administrator * */ public class AsyncImageLoader { private HashMap<String, SoftReference<Drawable>> imageCache;//图片缓冲 public AsyncImageLoader(){ imageCache = new HashMap<String, SoftReference<Drawable>>(); } /** * * @param imageUrl 图片地址 * @param imageView 需要设置drawable的view * @param imageCallback 回调接口 * @return */ public Drawable loadDrawable(final String imageUrl,final ImageView imageView,final ImageCallback imageCallback){ //如果有drawable对象,直接返回它的引用 if(imageCache.containsKey(imageUrl)){ SoftReference<Drawable> softReference = imageCache.get(imageUrl); Drawable drawable = softReference.get(); //对象有可能被系统回收了,需要判断是否为空 if(drawable != null){ return drawable; } } //如果没有,则重新下载 final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { imageCallback.imageLoaded((Drawable)msg.obj, imageView, imageUrl); super.handleMessage(msg); } }; //新建一个线程下载图片 new Thread(){ public void run() { Drawable drawable = Download.downloadDrawable(imageUrl); //将下载的图片保存到缓冲中 imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); }; }.start(); return null; } //回调接口,在这里面设置imageView的图片,直接imageView.setImageViewDrawable(imageDrawable); public interface ImageCallback{ public void imageLoaded(Drawable imageDrawable,ImageView imageView,String imgageUrl); } }
调用处的使用方法如下:
Drawable weibo_image = asyncImageLoader.loadDrawable( weibo.getThumbnail_pic(), weibo_ImgView, new ImageCallback() { @Override public void imageLoaded(Drawable imageDrawable, ImageView imageView, String imgageUrl) { imageView.setImageDrawable(imageDrawable); } }); if (weibo_image == null) { weibo_ImgView.setImageResource(R.drawable.trend_pic_loading); } else { weibo_ImgView.setImageDrawable(weibo_image); } }
相关文章推荐
- Android实现ListView异步加载图片
- ListView异步加载图片,完美实现图文混排
- Android 实现异步加载图片
- Android性能优化之实现双缓存的图片异步加载工具(LruCache+SoftReference) - 拿来即用
- android异步加载图片并缓存到本地实现方法
- 如何实现图片的异步加载
- 实现异步加载本地图片,防止oom错误
- Android异步加载学习笔记之三:用AsyncTask实现ListView中的图片数据加载
- 解决ListView滑动时卡的问题,实现异步加载图片解决
- 【代码笔记】iOS-实现网络图片的异步加载和缓存
- ListView异步加载图片,完美实现图文混排
- 利用DiskLruCache 实现异步加载图片
- Android 如何实现ListView异步加载网络图片
- iphone中使用NSoperation实现图片异步加载
- ListView异步加载图片,完美实现图文混排
- Android App中实现图片异步加载的实例分享
- Android实现ListView异步加载图片
- 使用ImageLoader实现图片异步加载
- Android实现ListView异步加载图片
- IOS中UITableView异步加载图片的实现