ListView优化之图片缓存优化

内容纲要


• ListView视图缓存优化
• ListView异步加载优化

• ListView图片缓存

• 内存优化

ListView图片缓存


如果每次加载列表时,都需要从网络下载图片,不但会消耗大量

的网络流量,而且会给用户不好的用户体验。为减少用户的

等待时间,可以对图片进行缓存,这里主要有两种缓存方案



1、临时缓存,当程序退出时,缓存会被清空。

2、本地持久化缓存,将图片保存在本地。


java] view plaincopyprint?public class AsyncImageLoader

{

private HashMap<String, SoftReference<Drawable>>

imageCache;


public AsyncImageLoader() {

imageCache = new HashMap<String,

SoftReference<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() {

@Override

public void handleMessage(Message message) {

imageCallback.imageLoaded((Drawable) message.obj,

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 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;

}


public static Drawable loadImageFromUrl(String url) {

// ...

}


public interface ImageCallback {

public void imageLoaded(Drawable imageDrawable, String imageUrl);


}


• 注意这里使用了 SoftReference来缓存图片,允许 GC在需要

的时候可以对缓存中的图片进行清理。它这样工作:


· 调用 loadDrawable(ImageUrl, imageCallback),传入一

个匿名实现的 ImageCallback接口


· 如果图片在缓存中不存在的话,图片将从单一的线程中下

载并在下载结束时通过 ImageCallback回调


· 如果图片确实存在于缓存中,就会马上返回,不会回调

ImageCallback
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值