Adapter 模板

要求所有的Adapter都继承自BaseAdapter,从构造函数注入List<自定义实体>这样的数据集合,从而完成ListView的填充工作,如下所示:

public class TemplateAdapter extends BaseAdapter {

    private Context context = null;
    private List entityList= null;

    public TemplateAdapter(Context context, List entityList) {
        this.context = context;
        this.entityList= entityList;
    }

    @Override
    public int getCount() {
        return entityList.size();
    }

    @Override
    public Object getItem(int position) {
        return entityList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (convertView== null) {
            convertView= LayoutInflater.from(context).inflate(R.layout.item_user_info, null);
            viewHolder = new ViewHolder();
            viewHolder.tvEmail= (TextView) convertView.findViewById(R.id.tv_email);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Entity entity = entityList.get(position);
        viewHolder.tvEmail.setText(entity.getEmail());
        return convertView;
    }

    static class ViewHolder {
        TextView tvEmail;
    }
}

对于每个自定义的Adapter,都要实现以下4个方法:

getCount();
getItem();
getItemId();
getView();

此外,还要内置一个Holder嵌套类,用于存放ListView中每一行中的控件。ViewHolder的存在,可以避免频繁创建同一个列表项,从而极大地节省内存。

你可能感兴趣的:(Adapter 模板)