标签:
Picasso是Square公司开源的一个Android图形缓存库,地址http://square.github.io/picasso/,可以实现图片下载和缓存功能。
它的使用及其的简单,仅仅只需要一行代码就能完全实现图片的异步加载:
Picasso.with(view.getContext()).load(newsItems.get(position).getThumb()).into(holder.ivHeader);//Picasso异步加载预览图
完全不需要任何其他操作便可以加载图片,而且自带缓存功能,还优化了在RecyclerView中的图片重复利用等问题,而且使用了复杂的图片压缩算法来减少内存消耗以及自带二级缓存
下面是博主在Adapter中写的范例:
1 package socialnews.linccy.com.socialnews.adapter; 2 3 import android.support.v7.widget.RecyclerView; 4 import android.view.LayoutInflater; 5 import android.view.View; 6 import android.view.ViewGroup; 7 import android.widget.ImageView; 8 import android.widget.TextView; 9 10 import com.squareup.picasso.Picasso; 11 12 import java.util.List; 13 14 import butterknife.BindView; 15 import butterknife.ButterKnife; 16 import socialnews.linccy.com.socialnews.utils.NewsItem; 17 import socialnews.linccy.com.socialnews.R; 18 19 /** 20 * Created by Lcc on 2016/7/9. 21 */ 22 23 public class NewsItemAdapter extends RecyclerView.Adapter<NewsItemAdapter.ViewHolder> { 24 25 private static List<NewsItem> newsItems; 26 private View view; 27 28 public NewsItemAdapter(List<NewsItem> newsItems) { 29 this.newsItems = newsItems; 30 } 31 32 @Override 33 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 34 view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_cardview_item, parent, false); 35 ViewHolder holder = new ViewHolder(view); 36 return holder; 37 } 38 39 @Override 40 public void onBindViewHolder(ViewHolder holder, int position) { 41 holder.tvTitle.setText(newsItems.get(position).getTitle()); 42 holder.tvDetail.setText(newsItems.get(position).getDescr()); 43 holder.tvTime.setText(newsItems.get(position).getTime()); 44 Picasso.with(view.getContext()).load(newsItems.get(position).getThumb()).into(holder.ivHeader);//Picasso异步加载预览图 45 } 46 47 @Override 48 public int getItemCount() { 49 return newsItems.size(); 50 } 51 52 53 public class ViewHolder extends RecyclerView.ViewHolder { 54 @BindView(R.id.iv_header) 55 ImageView ivHeader; 56 57 @BindView(R.id.tv_title) 58 TextView tvTitle; 59 @BindView(R.id.tv_detail) 60 TextView tvDetail; 61 @BindView(R.id.tv_time) 62 TextView tvTime; 63 64 public ViewHolder(View itemView) { 65 super(itemView); 66 ButterKnife.bind(this, itemView); 67 } 68 } 69 }
效果图:
标签:
原文地址:http://www.cnblogs.com/Linccy/p/5659084.html