我正在开发一个项目,我想通过按钮点击并在我的应用程序中显示来从服务器获取图像。请与我分享这个场景的代码。请帮帮我。
答案 0 :(得分:0)
以这种方式创建缓存机制:
/**
* Image caching used by volley image loader
* Created by tasneem on 23/7/15.
*/
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
@Override
public Bitmap getBitmap(String url) {
return get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
}
然后以这种方式加入你的VolleyControler:
import android.app.Application;
import android.text.TextUtils;
import android.util.Log;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.zingoy.app.ZingoyApplication;
/**
* Class for handling all network requests
* @author tasneem
*/
public class VolleyController extends Application {
public static final String TAG = VolleyController.class.getSimpleName();
private static VolleyController mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private VolleyController() {
mRequestQueue = mRequestQueue != null ? mRequestQueue : Volley.newRequestQueue(ZingoyApplication.getAppContext());
mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache());
}
public static synchronized VolleyController getInstance() {
mInstance = mInstance != null ? mInstance : new VolleyController();
return mInstance;
}
public RequestQueue getRequestQueue() {
Log.d(TAG, "Cancelling request");
return mRequestQueue != null ? mRequestQueue : Volley.newRequestQueue(getApplicationContext());
}
public ImageLoader getImageLoader() {
return mImageLoader != null ? mImageLoader : new ImageLoader(mRequestQueue, new LruBitmapCache());
}
}
无论何时想要渲染图像,都可以使用:
imageLayout.setImageUrl(url, VolleyController.getInstance().getImageLoader());