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


    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缓存加载就完成了。

  • 相关阅读:
    在String中添加移动构造函数和移动赋值运算符
    自定义String类,并且实现在STL容器中添加自定义的类型
    allocator例子
    Messages的例子
    java unicode转中文
    Oracle Unicode转中文(解码)
    dom4j解析XML
    如何下载HLS视频到本地(m3u8)
    background-position
    XMPP协议实现即时通讯底层书写 (二)-- IOS XMPPFramework Demo+分析
  • 原文地址:https://www.cnblogs.com/android-host/p/5390356.html
Copyright © 2020-2023  润新知