利用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中添加)ide

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

在MainActivity中實例化RequestQueue工具

RequestQueue mRequestQueue = Volley.newRequestQueue(this);

而後使用ImageLoader加載圖片gradle

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緩存加載就完成了。ui

相關文章
相關標籤/搜索