Generic ViewHolder for Android
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:
- Minimizes findViewById() calls
- Reuse Android convertView mechanism
Cons:
- Boilerplate: Manual put/pop
- 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:
- Still minimizes findViewById() calls
- Reuse Android convertView mechanism
- Single, reusable class for all Adapters
Cons:
- Boilerplate: Manual put/pop
- 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.