Volley提供了一个NetworkImageView类。java
利用NetworkImageView这个类,能够更有效率地去从网络去获取图片,由于它里面帮咱们多设置了一个缓存,但这缓存得本身实现。android
1)xml文件:缓存
<FrameLayout android:id="@+id/flImageContainer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/gvImages" android:layout_margin="30dp" > <com.android.volley.toolbox.NetworkImageView android:id="@+id/nivTestView" android:layout_width="100dp" android:layout_height="100dp" > </com.android.volley.toolbox.NetworkImageView> </FrameLayout>
2)Activity中使用:网络
networkImageView = (NetworkImageView) findViewById(R.id.nivTestView); mQueue = Volley.newRequestQueue(this); LruImageCache lruImageCache = LruImageCache.instance(); ImageLoader imageLoader = new ImageLoader(mQueue,lruImageCache); networkImageView.setDefaultImageResId(R.drawable.ic_launcher); networkImageView.setErrorImageResId(R.drawable.ic_launcher); networkImageView.setImageUrl(URLS[1], imageLoader);
3)实现LruImageCache类ide
package com.lms.volleydemo; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import com.android.volley.toolbox.ImageLoader.ImageCache; public class LruImageCache implements ImageCache{ private static LruCache<String, Bitmap> mMemoryCache; private static LruImageCache lruImageCache; private LruImageCache(){ // Get the Max available memory int maxMemory = (int) Runtime.getRuntime().maxMemory(); int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize){ @Override protected int sizeOf(String key, Bitmap bitmap){ return bitmap.getRowBytes() * bitmap.getHeight(); } }; } public static LruImageCache instance(){ if(lruImageCache == null){ lruImageCache = new LruImageCache(); } return lruImageCache; } @Override public Bitmap getBitmap(String arg0) { return mMemoryCache.get(arg0); } @Override public void putBitmap(String arg0, Bitmap arg1) { if(getBitmap(arg0) == null){ mMemoryCache.put(arg0, arg1); } } }