What is the ViewHolder pattern and how is it employed? What are some reasons for, and against, using it? What are some alternatives?
ViewHolder
design pattern is used to speed up rendering of your ListView - actually to make it work smoothly. Your code might call findViewById() frequently during the scrolling of ListView, which can slow down performance. Even when the Adapter returns an inflated view for recycling, you still need to look up the elements and update them.
A way around repeated use of findViewById() is to use the "view holder" design pattern, to hold the references to view elements for caching purposes. ViewHolder struct is stored in the target convert view via View.setTag(). When recycling a View, we can get the ViewHolder cache by (ViewHolder) convertView.getTag().
static class ViewHolder {
TextView titleView;
TextView subTitleTitleView;
ImageView iconView;
}
And then in getView()
of your Adapter class, cache its results:
ViewHolder holder = new ViewHolder();
holder.titleView = (TextView) convertView.findViewById(R.id.listitem_titleView);
convertView.setTag(holder);
And then RecyclerView is introduced in Android 5.1 (LOLLIPOP_MR1) which has built-in ViewHolder.