Thus, the well-known ViewHolder template usually looks like (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;
}
while the ViewHolder class usually looks like this:
static class ViewHolder{
public ImageView previewImage;
public TextView txtTitle;
public TextView txtDescription;
}
My questions are about the implementation of ViewHolder.
1) Why doesn't he use a constructor instead of initializing each individual field?
2) Why does it use the default access type instead of secure (in fact, it should be closed, but this affects performance due to the static accessories created by by JIT)? Well, I think it's only about inheritance.
So why the following pattern is not better (excluding the "protected vs default" access type):
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;
}
}
and the only change in the ListAdapter:
...
final TextView txtDescription = (TextView) convertView.findViewById(R.id.album_copyright);
viewHolder = new ViewHolder(albumImage, txtTitle, txtDescription);
convertView.setTag(viewHolder);
...
. ? - ?