Everybody who create Android application knows RecyclerView.Adapter. But when it comes to creating a list with different elements and multiple columns, not everyone solves this problem through the same adapter.
In this article I show how create such list and how we can use sealed classes for solve this problem. So turn on good music and tune on code writing! I think it will be interesting. The final result 👇
For start need divide this task on parts:
- For support different items we will create realization of RecyclerView.Adapter and will use getItemViewType method for create different ViewHolder’s.
- For create multiple column grid we will use standard GridLayoutManager with custom realization of GridLayoutManager.SpanSizeLookup.
Prepare / Let’s get started!
Firstly let’s create sealed class of our item. In this case some items contains static data (e.g. string/dimension/color resources). It may be useful in some cases, for example when you know final names of headers for sections. Other items have dynamic data which after implementation to your project will receive for example from server or database.
As you may notice parent class have parameter TestType:
- Make realization of getItemViewType function into single line, avoid using “when” select;
- Select which ViewHolder create for list item inside onCreateViewHolder function.
Last step of prepare everything for adapter is create layout’s and ViewHolder’s. I omitted this code because there is nothing special inside. But if you need it - link to test project will be at the end of article.
Everything done and we can start write code for adapter class which will connect all created classes together!
Also here created an interface named “Callback” which collect all interfaces of children ViewHolder’s. It’s made for prevent code overflow and also it’s very good for code reuse! If you will use some items in another adapter, for example, you only needed implement already existing ViewHolder callback in new adapter callback.
UnbindCallback is interface which realized in some ViewHolder’s. It’s needed for clear resources and for prevent memory leaks.
Create multiple column grid
A helper class to provide the number of spans each item occupies.
Inside this class us need override getSpanSize method, because documentation says (again 😃):
Returns the number of span occupied by the item at position.
And it’s all! Everything done for display such list on the screen. Thanks for reading and I hope this information will be useful! Don’t forget press 👏👏👏 if you like this.
Full code of this test project you may find here. Good luck!