Adapter代码
public class SpotsAdapter extends BaseAdapter{
private List<SpotsModel> mList;
private LayoutInflater inflater;
public SpotsAdapter(Context context,List<SpotsModel> list){
this.mList = list;
inflater = LayoutInflater.from(context);//传入context对象对其进行初始化
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int id) {
return id;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.spotslist_item, null);
holder = new ViewHolder(); //暂时存储ViewHolder中预定义的属性,类似于一个结构体
//下面几行将layout中的控件定义到这几个属性上
holder.img = (ImageView) convertView.findViewById(R.id.iv_img);
holder.name = (TextView) convertView.findViewById(R.id.txt_spotname);
holder.addr = (TextView) convertView.findViewById(R.id.txt_spotaddress);
convertView.setTag(holder); //将holder储存的各属性绑定到convertView
}
else{
holder = (ViewHolder) convertView.getTag();
}
//下面几行是对各字段赋值
holder.img.setImageResource(Util.getDrawableResourceID (mList.get(position).getSpotImg()));
holder.name.setText(mList.get(position).getSpotName());
holder.addr.setText(mList.get(position).getSpotAddr());
return convertView;
}
static class ViewHolder{
ImageView img;
TextView name;
TextView addr;
}
}
常见的优化手段:
- 重用ConvertView
- ViewHolder
- notifyDatasetChanged()
- 分批分页加载重用ConvertView