所以众所周知的 ViewHolder 模式通常看起来像(ListAdapter):
...
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final Album album = albums.get(position);
ViewHolder viewHolder = null;
if (convertView==null){
convertView = inflater.inflate(R.layout.albums_list_item, null);
final ImageView albumImage = (ImageView) convertView.findViewById(R.id.album_icon);
final TextView txtTitle = (TextView) convertView.findViewById(R.id.album_title);
final TextView txtDescription = (TextView) convertView.findViewById(R.id.album_copyright);
viewHolder = new ViewHolder();
viewHolder.albumImage = albumImage;
viewHolder.txtTitle = txtTitle;
viewHolder.txtDescription = txtDescription;
convertView.setTag(viewHolder);
}
else
viewHolder = (ViewHolder)convertView.getTag();
viewHolder.txtTitle.setText(album.getTitle(locale));
viewHolder.txtDescription.setText(album.getCopyrightInfo(locale));
...
return convertView;
}
而 ViewHolder 类通常看起来像:
static class ViewHolder{
public ImageView previewImage;
public TextView txtTitle;
public TextView txtDescription;
}
我的问题是关于 ViewHolder 的实现。
1)为什么不使用构造函数而不是初始化每个字段?
2)为什么它使用默认访问类型而不是受保护(实际上它必须是私有的,但这会由于 JIT 创建的静态访问器而影响性能)?好吧,我猜它只是关于继承。
那么为什么以下模式不是更好(不包括“保护与默认”访问类型):
protected static class ViewHolder{
public final ImageView previewImage;
public final TextView txtTitle;
public final TextView txtDescription;
public ViewHolder (final ImageView previewImage, final TextView txtTitle, final TextView txtDescription){
this.previewImage = previewImage;
this.txtTitle = txtTitle;
this.txtDescription = txtDescription;
}
}
ListAdapter 的唯一变化是:
...
final TextView txtDescription = (TextView) convertView.findViewById(R.id.album_copyright);
viewHolder = new ViewHolder(albumImage, txtTitle, txtDescription);
convertView.setTag(viewHolder);
...
无论如何,它必须调用构造函数。这只是品味问题吗?或者这个版本是否会以某种方式变慢,或者它会以某种方式影响性能?