Issue
I am writing a small social media app. I am loading my posts from a Rest Api. But in between the posts I would like to add some independent layouts what is the best way to do it?
eg the content of my recyclerView will be
Post
Post
Post
Some custom layout eg ask user for feedback
Post
Post
Suggest groups
Post
Post
Some custom Advert
Post
Post
I have tried looking at concatAdapter but it is mainly for sequential adapters.
Is there a way to inject a layout in between recyclerview Items. eg You add a layout between items at position 4 and 5 in the recyclerview.
Solution
RecylerView
supports different view types, so you have to create a model that encompass the 2 types and then map your BE data to your user interface model.
1.- Create the layouts:
- R.layout.post
- R.layout.user_feedback
We are going to use the ids later
2.- Create a model to support everything
sealed class Rows {
data class UiPost(...) : Rows()
data class UserFeedback(...): Rows()
}
- Make your adapter support different views
class UiPostViewHolder : RecyclerView.ViewHolder()...
class UserFeedbackViewHolder : RecyclerView.ViewHolder()...
class MyAdapter : ListAdapter<Rows, ViewHolder> {
override fun getItemView(position: Int) = when (getItem(position)) {
UiPost -> R.layout.post
UserFeedback -> R.layout.user_feedback
}
override fun onCreateViewHolder(...) {
return when(viewType) {
R.layout.post -> //instance the UiPostViewHolder
R.layout.user_feedback -> //inflate the view holder
}
}
}
4.- And you need a way to map your posts from BE to your new data structure, something like this
val mutableList = mutableList<Rows>()
backendPosts.forEach {
mutableList.add(UiPost(it.something, it.foo...))
if (it.confition) {
mutableList.add(UserFeedback(it..., it....))
}
}
return mutableList
Answered By - cutiko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.