At my current project we are in the middle of implementing filters for a shopping app. We have all kinds of filters: a slider for the price, checkboxes for the gender, etc. Basically the same stuff most shopping apps have these days. The challenge here for us was, that we wanted to show different type of filters in a list and be flexible about adding or removing a filter.

While planning the feature I remembered an article by Hannes Dorfmann. He wrote about something he called Adapter Delegates. It seemed like the perfect match for our case. In this post I want to show how you can combine this pattern with multibindings, but first let’s check the basics.

When setting up an adapter for our RecyclerView we overwrite usually the following methods.

You can already see that we get a parameter viewType when creating a ViewHolder. This information is what we need to support different views in our list. The adapter knows only one viewType until we define more. To do so we need to overwrite the following method.

So much for the theory, let’s get back to our filter scenario. In our case we have a list of data representing filters. So we would check for each position what kind of filter data we have and depending on it return another viewType. It’s quiet simple actually. But if you have many different viewTypes, you will have multiple Conditionals like the following all over your adapter.

That’s not the code, which would make our uncle Bob proud. Having the same conditional multiple times in a class is an indicator to refactor. What we want instead is to replace our Conditionals with Polymorphism. And that’s where finally the Adapter Delegates come into play !

The idea is to write a delegate class for each viewType. For our example case, I defined the following interface.

Each Delegate will have to provide the viewType it represents and a method to check if a certain filter data is represented by it. We will need this later in our adapter. But let’s first set up our Multibindings.

We define a map with all our Delegates and as a key, we will use an Integer to represent our viewType.

Now we can inject our map of viewTypes and delegates in our adapter.

The first thing we do in our adapter is to use our delegates to find the viewType for the current position.

We loop through our map to find the delegate which is representing our current filterData and then we return its viewType.

To create the ViewHolder we now only have to use the delegate which belongs to our current viewType.

Last but not least we bind our data to the viewHolder using our delegate. Here we are getting the viewType from our viewHolder.

That’s it ! We can now add or remove new filters by just updating our Multibindings map.

You can find the source code for this example here. The next part of this series will be about Activity behaviors, so stay tuned, thank you for reading and as always feedback is highly appreciated and feel free to connect.