FirebaseRecyclerAdapter with multiple ViewType
When we have started our app development using firebase and wanted to use RecyclerView, then first thing that came to our mind was how to achieve it with less effort.
Since firebase was a new thing to us, it was a challenging task for us to make RecyclerView work with firebase. The best thing we did is going for a well tested library (FirebaseUI) instead of writing it on our own.
Now we got another problem of achieving multiple view types using FirebaseRecyclerAdapter. Since it is very easy to achieve the same in default RecyclerView.Adapter, we thought of digging more into the source code of FirebaseRecyclerAdapter.
The problem with FirebaseRecyclerAdapter what we found is the way it is written can never support multiple view types.
By observing the above snippet, we can easily identify that it is inflating only one layout which is what we are passing when this object is getting created.
So to make it work with multiple view types, it is obvious that we have to override onCreateViewHolder to return multiple ViewHolder objects instead of just one.
It is obvious that we have to create multiple ViewHolder classes, so lets create those:
Now lets create the FirebaseRecyclerAdapter which supports multiple view type and enjoy:
Some points to note:
- Line #1: Pass RecyclerView.ViewHolder instead your own. Create your own ViewHolder in onCreateViewHolder depending upon the view type.
- Line #2: Note R.layout.item_user is just a dummy layout, since it will be ignored in onCreateViewHolder.
- Line #6: Have one flag in your model class itself to identify which type of view you need to draw in UI.
- Rest all are same as implementing a usual RecyclerView.Adapter.
Any better suggestion is always welcome.