The last ViewHolder you may need

Eric Lu
2 min readMar 4, 2017

--

With this library, you don’t need to create any custom ViewHolder classes any more!

When using the RecyclerView, it’s very common to create lots of custom RecyclerView.ViewHolders for every different item type. If there are 10 RecyclerView layouts in an app, and each RecyclerView has 5 different item types, we need in total 50 custom ViewHolder classes. It’s a bloated, repetitive, formulaic yet error-prone trend to create the 50 custom ViewHolder classes.

Old-fashioned way to create custom ViewHolder classes for every item type.

Again, the last ViewHolder library comes to the rescue.

The last ViewHolder library

With this library, you can create a ViewHolder and bind it like this way:

There is no need to create any one-time-use variables anymore. Use the setText, setOnClickListener, etc… methods which are provided in this library.

Custom OnItemClickListener Interfaces

Other than creating custom ViewHolder classes, it’s also a common occurrence to create custom OnItemClickListener interfaces to observe the click event of an item or a button in an item.

Here is what a simple item layout looks like:

a simple item layout

A common way to handle the click event is by creating an interface like this:

It’s simple, but it will bloat up your code if there are so many item types and components which want to handle click events.

The last ViewHolder library comes to the rescue again.

With this library, the only interface you would need is:

This interface is designed for any kind of RecyclerView item. There are only two methods, which are, onItemClick and onClick. The onItemClick method is for the whole item (except the clickable components like Button etc.), and the onClick method is for components inside an item (eg: the left and right button in the above example).

Using the OnRecyclerViewItemClickListener interface is simple as well. First, declare and implement it.

Next, pass the mListener to the RecyclerView.Adapter and use it to instantiate a ViewHolder instance.

That is it, a piece of cake, right?

In Conclusion

With this library, you:

  • No longer need to create custom RecyclerView.ViewHolder.
  • No longer need to create custom OnItemClickListener.
  • Have more time to enjoy your life.

The last ViewHolder library

If you enjoyed this post, please show your support! Recommend, follow, comment, share.

This really means a lot!

--

--