Picasso库是一个高性能的第三方图片下载库,
使用该库时,可以简单地完成图片的下载、缓存等功能。
其使用方法如下所示,以RecyclerView为例:
//定义RecyclerView的Adapter
private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder> {
private List<GalleryItem> mGalleryItems;
PhotoAdapter(List<GalleryItem> galleryItems) {
mGalleryItems = galleryItems;
}
@Override
public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(R.layout.gallery_item, parent, false);
return new PhotoHolder(view);
}
@Override
public void onBindViewHolder(PhotoHolder holder, int position) {
GalleryItem galleryItem = mGalleryItems.get(position);
holder.bindGalleryItem(galleryItem, position);
}
@Override
public int getItemCount() {
return mGalleryItems.size();
}
}
//定义RecyclerView的ViewHolder
private class PhotoHolder extends RecyclerView.ViewHolder {
private ImageView mItemImageView;
private TextView mTextView;
PhotoHolder(View itemView) {
super(itemView);
mItemImageView = (ImageView) itemView.findViewById
(R.id.fragment_photo_gallery_image_view);
mTextView = (TextView) itemView.findViewById
(R.id.fragment_photo_gallery_text_view);
}
void bindGalleryItem(GalleryItem galleryItem, int position) {
mTextView.setText(getString(R.string.text_title, "" + position));
//重点代码在此!!!!
//Picasso库,with中传入Context
Picasso.with(getActivity())
//load中传入下载图片的地址
.load(galleryItem.getThumbURL())
//选择性使用,指定图片未下载时的占位图
.placeholder(R.drawable.place_holder)
//指定下载图片应该放置的布局位置
.into(mItemImageView);
}
}
使用上述方法后,Picasso库将在视图加载时,自动完成从缓存的读取,或进行实际的下载工作。