我试图将下载的图像缓存在主视图上,并在详细视图中显示它们。我测试的方法如下:首先,我在gridview上显示所有图像,并断开Internet连接,并希望查看详细信息上的缓存图像。但是,在详细信息活动中,未显示图像。
我正在使用以下Volley Singleton类,如下所示:
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
CustomVolleyRequest.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(context.getApplicationContext(), 10 * 1024 * 1024);
}
return requestQueue;
}
ImageLoader getImageLoader() {
return imageLoader;
}
}
主活动适配器
public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item, parent, false);
}
holder.imageView.setImageUrl(imageURL, mImageLoader);
}
详细活动
// I have checked and confirmed that the following url is same with the one the main activity
String url = getArguments().getString("image_url");
ImageLoader imageLoader = CustomVolleyRequest.getInstance(getContext()).getImageLoader();
mImageView.setImageUrl(url, imageLoader);
最佳答案
我认为Volley缓存仍然可以使用,但是,您的问题是由于detail活动中的NetworkImageView
与主活动中的NetworkImageView
不同,它还需要一次成功地成功加载图像。在这里,您可以在开始详细活动之前先断开Internet连接。
您可以看到NetworkImageView.java内部的逻辑
注意#122中的行
// if there was an old request in this view, check if it needs to be canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {...
和#134
// The pre-existing content of this view didn't match the current URL. Load the new image
// from the network.
ImageContainer newContainer = mImageLoader.get(mUrl,...
更新2017/02/10
当
NetworkImageView
内部详细信息活动从网络(ImageContainer newContainer = mImageLoader.get...
)加载新图像时,将调用ImageLoader.java内部的get
方法。看代码:
...
final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight);
// Try to look up the request in the cache of remote images.
Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
// Return the cached bitmap.
ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
imageListener.onResponse(container, true);
return container;
}
...
您将发现,如果两个活动中的图像视图具有相同的宽度和高度,则
cacheKey
也将相同,并且cachedBitmap
将不为null,缓存的位图将用于NetworkImageView
内部详细信息活动也。