我想知道检查是否ViewHolder
使用相同的模型对象是一个很好的优化。这适用于填充View
返回的getView()
.
这假设视图内容没有改变——我认为这是常见的情况。
例如,标准模式是:
public View getView(int position, View convertView, ViewGroup parent) {
Model model = models.get(position);
if (convertView != null) {
// View was recycled. Get the holder.
viewHolder = (ViewHolder) convertView.getTag();
} else {
// Inflate a new layout and create a holder
convertView = inflater.inflate(R.layout.item_layout, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.img = (ImageView) convertView
.findViewById(R.id.img);
convertView.setTag(viewHolder);
}
// Fill in the content
Bitmap imgBitmap = loadBitmapFor(model.getName());
if (imgBitmap != null) {
viewHolder.img.setVisibility(View.VISIBLE);
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolder.img.setImageBitmap(imgBitmap);
}
viewHolder.name.setText(model.getName());
return convertView;
}
static class ViewHolder {
TextView name;
ImageView img;
}
我们通过检查是否ListView
在同一位置查看同一对象来进行优化:
public View getView(int position, View convertView, ViewGroup parent) {
Model model = models.get(position);
boolean recycled;
if (convertView != null) {
// View was recycled. Get the holder.
viewHolder = (ViewHolder) convertView.getTag();
recycled = true;
} else {
// Inflate a new layout and create a holder
convertView = inflater.inflate(R.layout.item_layout, null);
viewHolder = new ViewHolder();
viewHolder.model = model;
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.img = (ImageView) convertView
.findViewById(R.id.img);
convertView.setTag(viewHolder);
recycled = false;
}
// Skip the expensive content loading if we can
if (recycled && (model == viewHolder.model) && (position == viewHolder.position)) {
return convertView;
}
// Fill in the content
Bitmap imgBitmap = loadBitmapFor(model.getName());
if (imgBitmap != null) {
viewHolder.img.setVisibility(View.VISIBLE);
viewHolder.img.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolder.img.setImageBitmap(imgBitmap);
}
viewHolder.name.setText(model.getName());
return convertView;
}
static class ViewHolder {
int position; // for double checking_
Model model;
TextView name;
ImageView img;
}