我使用volley在android中加载图像和缓存图像。我想在缓存请求图像时从缓存加载图像。所以我用下面的方法设置我的图像视图。
public void setImage(String url)
{
final ImageRequest imgRequest = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
img_thumb.setImageBitmap(response);
}
}, 0, 0, ImageView.ScaleType.FIT_XY, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//img_thumb.setBackgroundColor(Color.parseColor("#ff0000"));
error.printStackTrace();
}
});
MyApplication.getInstance().addToRequestQueue(imgRequest);
}
但我不知道如果从缓存中获得该图像,如何从缓存中加载?
答案 0 :(得分:0)
如果您提供了使用有效ImageLoader
对象创建的ImageCache
,Volley将在触发图像请求时自动从缓存中提取位图:
mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mMemCache = new LruCache<String, Bitmap>(CACHE_SIZE);
@Override
public Bitmap getBitmap(String url) {
return mMemCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mMemCache.put(url, bitmap);
}
});
然后,要加载图片,请使用您创建的ImageLoader
:
/**
* Performs a request to load an image from a given url.
* @param url the url to load the image from.
* @param listener the listener which will receive a call once the image load finishes (either with success or failure). The listener is called on the UI thread.
* @param maxWidth the max width (in pixels) of the requested image. The returned bitmap will not exceed this width. Use 0 for unlimited
* @param maxHeight the max height (in pixels) of the requested image. The returned bitmap will not exceed this height. Use 0 for unlimited.
* @return an ImageContainer object which can be used to access the bitmap once the request has completed, or to cancel the request before it completes.
*/
public ImageLoader.ImageContainer loadImageFromUrl(final String url, final ImageRequestListener listener, int maxWidth, int maxHeight) {
if (url == null || Uri.parse(url) == null || Uri.parse(url).getHost() == null) {
Logger.e("VolleyManager: loadImageFromUrl: invalid url " + url);
listener.onImageLoadFailed();
return null;
}
return mImageLoader.get(url, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
if (listener != null && response.getBitmap() != null) {
listener.onImageLoadComplete(response.getBitmap());
} else if (listener != null) {
listener.onImageLoadFailed(;
}
}
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.onImageLoadFailed();
}
}
}, maxWidth, maxHeight);