adapter优化

Adapter是ListView界面与数据之间的交互桥梁,当列表里的每一项显示到页面时,都会调用Adapter的getView方法返回一个View。
一般写法
public View getView(int position, View convertView, ViewGroup parent) {
View item = mInflater.inflate(R.layout.list_item_icon_text, null);
((TextView) item.findViewById(R.id.text)).setText(DATA[position]);
((ImageView) item.findViewById(R.id.icon)).setImageResource(R.drawable.icon);
return item;
}


我们可以进一步优化:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(DATA[position]);
holder.icon.setImageResource(R.drawable.icon);
return convertView;
}
 
static class ViewHolder {
TextView text;
ImageView icon;
}

你可能感兴趣的:(Adapter)