A merge adapter has been introduced recently and you can implement it in your project now. However, I’d also like to point out that a lot of people have some doubts in using it. I’ll show you in this article difference between a new approach of implementation elements with different types (Merge Adapter) and an old approach (Multi ViewHolders).
For using MergeAdapter you should add implementation “androidx.recyclerview:recyclerview:1.2.0-alpha02” in build.gradle. You can get the last version here.
I’ll show you how you can use it via a simple project. If this information is not enough, you’ll be able to look at the documentation.
Let’s create two models.
The first model is for header item.
class User(var id: Int, var avatar: Int, var name: String, var lastname: String)
The second model is for usual item.
class Employee(var id: Int, var position: String)
I’d like to emphasize that for header and usual item we need to create the separate adapters. At the beginning create the header adapter.
After it create the second adapter
headerAdapter = HeaderAdapter(listOf(userRepository.getUser()))
contentAdapter = ContentAdapter(employeesRepository.getEmployees())
mergeAdapter = MergeAdapter(headerAdapter, contentAdapter)
recyclerView.adapter = mergeAdapter
You can see that the logic of was extracted to separated adapters. And after initialization of recycler view you should merge adapters via constructor of MergeAdapter.
Now I’ll show you an old approach for this task.
You can see that this adapter has a lot of information. It would be fair to say that it’s a very simple example in my article. In reality you face with complicated items and a list can contain footer item. In old approach an adapter stores too much logic.
We can’t deny the fact that code such adapters contain not reusable components (header, footer) and it break single responsibility principle.
It goes without saying that these disadvantages should be fixed and Merge Adapter perfectly does it.
You can find all project on Github :