1.使用OkHttp獲取到JSON數(shù)據(jù)并解析
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);
}
};
//訪問網(wǎng)絡圖片并提醒主線程更新UI
public void showImageFormURL(ImageView imageView,String urlString){
//獲取ListView中的imageView
mImageView=imageView;
//封裝過的OkHttp訪問網(wǎng)絡圖片方法
HttpUtil.DownloadImage(urlString, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//將取得的字符流轉(zhuǎn)化為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中調(diào)用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);
}