继承BaseAdapter

作者: Jennyni1122 | 来源:发表于2019-01-28 11:44 被阅读16次

    开发过程中经常用到ListView,因此适配器要非常熟练。因为模式相对固定,所以截取一段代码作为参考:

    public class NewsListAdapter extends BaseAdapter {
        private List<NewsBean.ResultBean.DataBean> data;
        private Context context;
    
        public NewsListAdapter(List<NewsBean.ResultBean.DataBean>  data, Context context) {
            this.data = data;
            this.context = context;
    
        }
    
        public void setData(List<NewsBean.ResultBean.DataBean> data) {
            this.data = data;
        }
    
        @Override
        public int getCount() {
            return data.size();
        }
    
        @Override
        public Object getItem(int position) {
            return position;
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
             View view;
             ViewHolder holder;
            if (convertView == null){
                view = View.inflate(context, R.layout.item_news,null);
                holder = new ViewHolder();
                holder.ivIcon= (ImageView) view.findViewById(R.id.iv_icon);
                holder.tvTitle= (TextView) view.findViewById(R.id.tv_title);
                holder.tvFrom= (TextView) view.findViewById(R.id.tv_from);
                holder.tvDate= (TextView) view.findViewById(R.id.tv_date);
                view.setTag(holder);
            }else { //复用convertView
                view = convertView;
                holder = (ViewHolder) view.getTag();
            }
    
            //数据填充
            NewsBean.ResultBean.DataBean dataBean = data.get(position);
            holder.tvTitle.setText(dataBean.getTitle());
            holder.tvFrom.setText(dataBean.getAuthor_name());
            holder.tvDate.setText(dataBean.getThumbnail_pic_s());
            if (!TextUtils.isEmpty(dataBean.getThumbnail_pic_s())){
                Picasso.with(context)
                    .load(dataBean.getThumbnail_pic_s())
                        .placeholder(R.drawable.zhanwei)
                        .error(R.drawable.zhanwei)
                        .into(holder.ivIcon);   //图片
            }
            return view;
        }
    
        private static class ViewHolder{
            ImageView ivIcon;
            TextView tvTitle,tvFrom,tvDate;
    
        }
    }
    
    

    相关文章

      网友评论

        本文标题:继承BaseAdapter

        本文链接:https://www.haomeiwen.com/subject/zfqujqtx.html