OkHttp异步加载访问网络图片思路-listview

1.使用OkHttp获取到JSON数据并解析

2.新建ImageLoader类用于加载ListView中的图片 

public class ImageLoader {

private ImageView mImageView;

//用于异步更新UI

private Handler handler =new Handler(){

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

mImageView.setImageBitmap((Bitmap)msg.obj);

}

};

//访问网络图片并提醒主线程更新UI

public void showImageFormURL(ImageView imageView,String urlString){

//获取ListView中的imageView

mImageView=imageView;

//封装过的OkHttp访问网络图片方法

HttpUtil.DownloadImage(urlString, new Callback() {

@Override

public void onFailure(Call call, IOException e) {

}

@Override

public void onResponse(Call call, Response response) throws IOException {

//将取得的字符流转化为Bitmap

InputStream is =response.body().byteStream();

Bitmap bitmap=BitmapFactory.decodeStream(is);

Log.e(TAG, "onResponse: "+bitmap);

//将Bitmap以message形式传递给handler更新UI

Message message = Message.obtain();

message.obj =bitmap;

handler.sendMessage(message);

}

});

}

3.在Adapter中调用ImageLoader类的showImageFormURL(ImageView imageView,String urlString)方法

@Override

public voidonBindViewHolder(ViewHolder holder,intposition) {

Order order =mOrderList.get(position);

holder.idTv.setText(order.getId());

holder.nameTv.setText(order.getName());

String imageUrl ="images/"+order.getImage();

new ImageLoader().showImageFormURL(holder.iconIv,imageUrl);

}

推荐阅读更多精彩内容