ViewHolder holder = null;
if(convertView == null){
convertView = mInflater.inflate(R.layout.xxx null);
holder = new ViewHolder();
holder.tvXXX = (TextView)findViewById(R.id.xxx);
//...一连串的findViewById
}
else{
holder = (ViewHolder) convertView.getTag();
}
private static class ViewHolder{
TextView tvXXX;
//很多view的定义
}
简洁写法
public class ViewHolder {
// I added a generic return type to reduce the casting noise in client code
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
}
在getView里这样
@Override public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.banana_phone, parent, false);
}
ImageView bananaView = ViewHolder.get(convertView, R.id.banana);
TextView phoneView = ViewHolder.get(convertView, R.id.phone);
BananaPhone bananaPhone = getItem(position);
phoneView.setText(bananaPhone.getPhone());
bananaView.setImageResource(bananaPhone.getBanana());
return convertView;
}
SparseArray:优化过的存储integer和object键值对的hashmap,使用折半查找,并优化了内存分配
ViewHolder Partten是把一个自定义类绑定到一个view,这种是把SparseArray绑定到一个view,虽然SparseArray 初始化会分配10长度的地址,理论上貌似浪费了内存,理论上插入和删除操作也是有时间损耗的,但是这些都在允许范围内。
其实可以加一个私有构造函数防止外部实例化
private ViewHolder(){
}
参考:http://www.eoeandroid.com/thread-321547-1-1.html