Generic ViewHolder for Android

Alexey Buzdin
1 min readSep 9, 2014

--

ListViews and Adapters are one of the most common Android classes in Android project and if not handled properly are the ones that can cause your app a serious performance loss.

One of the tips to smoothen AdapterView scrolling is ViewHolder pattern, that will ease some computation from UI thread. At first glance findViewById() method seems to be a harmlessly used here and there, but with Adapters it can be a real threat to performance. ViewHolder lets you minimize the findViewById() calls in UI thread during scrolling and smoothen its overall UX.

Example of simple ViewHolder usage:

Pros:

  1. Minimizes findViewById() calls
  2. Reuse Android convertView mechanism

Cons:

  1. Boilerplate: Manual put/pop
  2. Boilerplate: Additional maintainable class per Adapter

If your are tired of maintaining your ViewHolders in the project, but want to retain the performance gain, then its time to use a generic ViewHolder:

It features some fancy methods and can be reused in different places, for example it can be easily ported into cross-compile frameworks like Xamarin.Android without much hassle.

Example of generic ViewHolder usage:

Pros:

  1. Still minimizes findViewById() calls
  2. Reuse Android convertView mechanism
  3. Single, reusable class for all Adapters

Cons:

  1. Boilerplate: Manual put/pop
  2. SparseArray is slightly slower than manual ViewHolder

Conclusion

ViewHolder does indeed help with performance of AdapterViews, but offers yet more Android boilerplate in our code. Generic ViewHolder is a simple and tidy solution for it, but still has some issues.

Ideally we need a compile time ViewHolder generation, akin to Dagger or use a more wrappery wrapper of BaseAdapter.

--

--

Alexey Buzdin

Java / Mobile developer at C.T.Co and GDG Riga co-organizer. Passionate for new technology and software craftsmanship.