NetworkImageView 分析:public class NetworkImageView extends ImageView 他继承自ImageView,并且添加了一个新方法: public void setImageUrl(String url, ImageLoader imageLoader) {}该参数包含一个Url地址和一个ImageLoader对象
还有一个核心方法
private void loadImageIfNecessary(final boolean isInLayoutPass) {}
内部实现,boolean 类型参数代表是否重新请求网络 ,true:重新请求 false:取缓存
内部实现和 ImageLoader类似,都是通过ImageContainer中new一个ImageListener,在ImageListener,只是做了 Url的空判断,如果Url为null,则调用ImageContainer.cancelRequest();取消请求
同时覆盖以下几个方法
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//onLayout时重新请求
loadImageIfNecessary(true);
}
@Override
protected void onDetachedFromWindow() {
//销毁View的时候Release操作
if (mImageContainer != null) {
// If the view was bound to an image request, cancel it and clear
// out the image from the view.
mImageContainer.cancelRequest();
setImageBitmap(null);
// also clear out the container so we can reload the image if necessary.
mImageContainer = null;
}
super.onDetachedFromWindow();
}
//drawable状态改变重绘
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
总结:网络请求下载图片显示,可以使用此控件,比传统的ImageView多了网络处理,也添加了2个方法,设置开始下载的默认图和下载出错后显示图
/**
* Sets the default image resource ID to be used for this view until the attempt to load it
* completes.
*/
public void setDefaultImageResId(int defaultImage) {
mDefaultImageId = defaultImage;
} /**
* Sets the error image resource ID to be used for this view in the event that the image
* requested fails to load.
*/
public void setErrorImageResId(int errorImage) {
mErrorImageId = errorImage;
}