查漏补缺之继承BaseAdapter

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

public class NewsListAdapter extends BaseAdapter {
    private List data;
    private Context context;

    public NewsListAdapter(List  data, Context context) {
        this.data = data;
        this.context = context;

    }

    public void setData(List 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)