Universal Image Loader异步显示图片的完美封装

我们在使用Universal Image Loader的时候可能会有显示不同默认图片的需求,采用下面封装来实现事半功倍,其中RoundedImageView继承ImageView的圆角图片控件AsyncRoundedImageView 继承RoundedImageView,获取自定义属性实现对Universal Image Loader显示的封装,话不多说,上源码。



public class AsyncRoundedImageView extends RoundedImageView {

private Drawable mImageOnLoading;
private Drawable mImageOnFail;
private Drawable mImageForEmpty;


private boolean hadLoaded;

public AsyncRoundedImageView(Context context) {
super(context);
}

public AsyncRoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
TypedArray a = context.obtainStyledAttributes(attrs, 
R.styleable.AsyncImageView); 

mImageForEmpty = a.getDrawable(R.styleable.AsyncImageView_image_for_empty_url);
mImageOnLoading = a.getDrawable(R.styleable.AsyncImageView_image_on_loading);
mImageOnFail = a.getDrawable(R.styleable.AsyncImageView_image_on_fail);

a.recycle();
}

public void setImageForEmptyUrl(Drawable drawable) {
mImageForEmpty = drawable;
}

public void setImageOnLoading(Drawable drawable) {
mImageOnLoading = drawable;
}

public void setImageOnFail(Drawable drawable) {
mImageOnFail = drawable;
}

public void displayImage(String uri) {
displayImage(uri, null, null);
}

public void displayImage(String uri, ImageLoadingListener listener) {
displayImage(uri, null, listener);
}

    //异步显示图片
public void displayImage(String uri, DisplayImageOptions options, ImageLoadingListener listener) {
if (uri == null) {
return;
}
if (null == options) {
options = getOptions();
}
hadLoaded = true;
ImageLoader.getInstance().displayImage(uri, this, options, listener);
}

private DisplayImageOptions getOptions() {
DisplayImageOptions.Builder builder = new Builder();
builder.bitmapConfig(Bitmap.Config.RGB_565);
builder.cacheInMemory(true);
builder.cacheOnDisc(true);
builder.imageScaleType(ImageScaleType.EXACTLY);
if (mImageOnLoading != null && !hadLoaded) {
builder.showImageOnLoading(mImageOnLoading);
}
if (mImageOnFail != null) {
builder.showImageOnFail(mImageOnFail);
}
if (mImageForEmpty != null) {
builder.showImageForEmptyUri(mImageForEmpty);
}


return builder.build();
}


}

你可能感兴趣的:(Universal Image Loader异步显示图片的完美封装)