您的位置:首页 > 其它

利用Volley封装好的图片缓存处理加载图片

2016-04-14 11:20 411 查看
Volley 工具箱中提供了一种通过
DiskBasedCache
类实现的标准缓存。这个类能够缓存文件到磁盘的指定目录。但是为了使用
ImageLoader
,我们应该提供一个自定义的内存 LRC bitmap 缓存,这个缓存实现了
ImageLoader.ImageCache
接口。

首先创建一个自定义的内存LRC bitmap缓存:

/**
* Created by John on 2016/4/14.
*/
public class LruBitmapCache extends LruCache<String,Bitmap> implements ImageLoader.ImageCache {

public LruBitmapCache(int maxSize) {
super(maxSize);
}
public LruBitmapCache(Context context){
this(getCacheSize(context));
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url,bitmap);
}

@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
public static int getCacheSize(Context ctx) {
final DisplayMetrics displayMetrics = ctx.getResources().
getDisplayMetrics();
final int screenWidth = displayMetrics.widthPixels;
final int screenHeight = displayMetrics.heightPixels;
// 4 bytes per pixel
final int screenBytes = screenWidth * screenHeight * 4;

return screenBytes * 3;
}
}


在studio中导入velley包(直接在build.gradle中添加)

compile 'com.mcxiaoke.volley:library-aar:1.0.0'


在MainActivity中实例化RequestQueue

RequestQueue mRequestQueue = Volley.newRequestQueue(this);


然后使用ImageLoader加载图片

ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(LruBitmapCache.getCacheSize(this)));
mImageLoader.get(PNG_URL,ImageLoader.getImageListener(imageView1,R.mipmap.ic_launcher,R.mipmap.error));//PNG_URL是要加载的图片的地址,imageView1 是图片加载的view,图片未加载出来时显示ic_launcher,如果遇到网络错误或者加载失败则显示error。


一个简单的网络or缓存加载就完成了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: