Last active
December 23, 2015 06:49
-
-
Save stackoverflows/6596554 to your computer and use it in GitHub Desktop.
Volley Image Wrapper used with standard Android ImageViews ( android.widget.ImageView)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.exampleapp; | |
import android.widget.ImageView; | |
import com.android.volley.RequestQueue; | |
import com.android.volley.VolleyError; | |
import com.android.volley.toolbox.ImageLoader; | |
import com.android.volley.toolbox.ImageLoader.ImageContainer; | |
public final class VolleyImageWrapper { | |
private static ImageLoader imageLoader = null; | |
public static ImageLoader getImageLoader() { | |
if (imageLoader == null) { | |
RequestQueue requestQueue = VolleyRequestTask.getRequestQueue(); | |
imageLoader = new ImageLoader(requestQueue, new BitmapLruCache()); | |
} | |
return imageLoader; | |
} | |
/** | |
* Helper method to load remote image into an ImageView asynchronously via Volley. The size of the ImageView is used to indicate the maximum size to Volley | |
* @param url The url to load the image from | |
* @param imageView The imageView to display the image into (as well as the loading/error resources) | |
* @param loadingResourceId The drawable resource id to display while the image is being retrieved. A value of 0 will not display a loading image. | |
* @param errorResourceId The drawable resource id to display if there is an error. A value of 0 will not display an error image. | |
* @return an ImageContainer object that can be used to cancel the request. | |
*/ | |
public static ImageContainer loadIntoImageView(final String url, final ImageView imageView, final int loadingResourceId, final int errorResourceId) { | |
if (imageView == null) | |
return null; | |
ImageLoader.ImageContainer imageContainer = getImageLoader().get(url, new ImageLoader.ImageListener() { | |
public void onErrorResponse(VolleyError arg0) { | |
if (errorResourceId > 0) // set an error image if the download fails | |
imageView.setImageResource(errorResourceId); | |
} | |
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) { | |
if (response.getBitmap() != null) { | |
imageView.setImageBitmap(response.getBitmap()); | |
} else { | |
if (loadingResourceId > 0) | |
imageView.setImageResource(loadingResourceId); | |
} | |
} | |
}, imageView.getWidth(), imageView.getHeight()); | |
return imageContainer; | |
} | |
/** | |
* @see loadIntoImage(String, ImageView, int, int); | |
*/ | |
public static ImageContainer loadIntoImageView(final String url, final ImageView imageView) { | |
return loadIntoImageView(url, imageView, 0, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment