Implementing ConcatAdapter In Android
TL;DR
Let’s say the designer team give you a design as above screenshot. The first idea is using RecyclerView with multiple view types inside, but it will be a lot of view types that you need to manage.
Sine recyclerview:1.2.0-alpha04, ConcatAdapter is introduced that presents the contents of multiple adapters in sequence.
Integration
Add the dependencies for the artifacts you need in the build.gradle
file for your app or module:
dependencies {
implementation "androidx.recyclerview:recyclerview:1.2.0-alpha04"
}
For example, we need to show a header layout as user info, a note, then a list of photos. We will create three different adapters:
HeaderAdapter
NoteAdapter
GalleryAdapter
We can merge these three adapters by using constructor or just add one by one:
val concatAdapter = ConcatAdapter()
concatAdapter.addAdapter(characterAdapter)
concatAdapter.addAdapter(noteAdapter)
concatAdapter.addAdapter(galleryAdapter)with(rvData) {
adapter = concatAdapter
}
In main layout, we will add a recyclerView:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvData"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</FrameLayout>
Keynote
- By default, each added adapter will have its own isolated pool of
RecyclerView.ViewHolder
s, with no re-use in between added adapters.
If your RecyclerView.Adapter
s share the same view types, and can support sharing RecyclerView.ViewHolder
s between added adapters, provide a config like this:
val config = ConcatAdapter.Config.Builder().setIsolateViewTypes(true)
.build()
val concatAdapter = ConcatAdapter(config)
2. We can remove an adapter by:
concatAdapter.removeAdapter(noteAdapter)
Conclusion
It’s an alpha version of development, there may be changed or removed in next version, so consider to use.
You can find the sample code here.
Happy coding!