待实现的
接口
class="java">
public interface ImageCallback {
void imageLoad(Drawable image,String imageUrl);
}
回调接口的方法
//参数有一个实现回调接口的imageCallback对象
public Drawable loadDrawable(final String imageUrl,final ImageCallback imageCallback){
Log.i("AsyncLoadImage", "loadDrawable()"+imageUrl);
//如果缓存中有则从缓存中取出来
if(imageCache.containsKey(imageUrl)){
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
if(softReference.get()!=null){//判断是否有drawable
return softReference.get(); //有则返回
}
}
//使用线程池下载图片
executorService.submit(new Runnable(){
@Override
public void run() {
try {
// final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.jpg");
final Drawable drawable = getDrawableFormUrl(imageUrl); //调用获取数据的方法
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));//将加载的图片放入到内存中
mHandler.post(new Runnable(){
@Override
public void run() {
//调用回调接口的方法,已由imageCallback实现!
imageCallback.imageLoad(drawable,imageUrl);//接口回调
}
});
} catch (Exception e) {
throw new RuntimeException();
}
}
});
return null ;
}
一个列表适配器的getview方法,已重写
@Override
public View getView( int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView()");
if(convertView == null){
//获取布局
convertView = LayoutInflater.from(cext).inflate(R.layout.item_image, null);
//获取布局里面的ImageView组件
final ImageView imageView = (ImageView)convertView.findViewById(R.id.item_imageView);
//获取当前的图片的url地址
final String url = urlList.get(position).getImageUrl();
//为图片设置一个tag 这个很重要这样的目的是为了控制每个ImageView组件都显示对应的图片
imageView.setTag(url);
Log.i(TAG, "初始化"+(position));
//开始异步加载图片
//[color=red]实例化一个实现接口的对象,供上一段代码loadDrawable调用[/color]
Drawable drawable = asyncLoadImage.loadDrawable(url, new AsyncLoadImage.ImageCallback(){
@Override
public void imageLoad(Drawable image,String imageUrl) {
//判断当前的url地址是否为当前组件的url地址 是则加载图片
if(imageUrl.equals(imageView.getTag())){
imageView.setImageDrawable(image);
}
}
});
}else{
Log.i(TAG, "完成后的初始化"+(position));
final ImageView imageView = (ImageView)convertView.findViewById(R.id.item_imageView);
final String url = urlList.get(position).getImageUrl();
imageView.setTag(url);
Drawable drawable = asyncLoadImage.loadDrawable(url, new AsyncLoadImage.ImageCallback(){
@Override
public void imageLoad(Drawable image,String imageUrl) {
if(imageUrl.equals(imageView.getTag())){
imageView.setImageDrawable(image);
}
}
});
}
return convertView;
}