利用Volley封装好的图片缓存处理加载图片
2016-04-14 11:20
411 查看
Volley 工具箱中提供了一种通过
首先创建一个自定义的内存LRC bitmap缓存:
在studio中导入velley包(直接在build.gradle中添加)
在MainActivity中实例化RequestQueue
然后使用ImageLoader加载图片
一个简单的网络or缓存加载就完成了。
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缓存加载就完成了。
相关文章推荐
- 二、Android Studio使用——导入jar包,运行、debug都不是问题
- 加快Android编译速度
- 【系统维护篇】 之 从零开始
- C++对象模型(剖析虚函数表)
- android 如何获取连接wifi热点的设备数量
- Matlab中的括号()[]{}
- centos 安装spark
- String类型与其他类型的相互转换
- HttpResponse 内容解压
- 隐藏底部的tabbar
- 《Android性能优化》学习笔记链接<转载>
- 环境搭建以及使用Ember.js创建第一个静态页面
- Electron框架学习笔记一
- QwtPlot简单使用
- Linux服务器搭建jenkins
- Error building Player: CommandInvokationFailure: Unable to convert classes into dex format. See the
- 设计原则概念总结
- 设计模式:模式和原则
- tomcat中catalina是什么
- 指针数组与数组指针