I am using all Android architecture components in my project (Room DB, Live Data etc.) Currently, I am facing a problem that I have RecyclerView which should used loaded data from Room DB and display it with Paging library. The problem is that there is a multiple data classes which represents the items in newsfeed and are stored in Room and I need display them in that one recycler.
Is there any way how to easily solve it? Can I for example create some interface which would be used by all these classes?
onCreateViewHolder(parent: ViewGroup, viewType: Int) In onCreateViewHolder, we will inflate the view that we will be using to hold each list item. This method will be called when RecyclerView needs a new ViewHolder of the given type to represent. The params are the Viewgroup parent and int viewType.
You could create and interface
public interface NeewsFeedItem
String getTitle();
int getType();
String data();
...
Each of your model implement NeewsFeedItem
and inside your Adapter you decide what type of view to show and how to show the proper NeewsFeedItem
.
You could override getItemViewType to show different presentation for different NeewsFeed's types.
Also you could check FlexibleAdapter library that could help to manage your adapter with different types, headers, footers etc.
You can provide multiple View holder to list by overriding getItemViewType() method of RecyclerView.Adapter.
Code Snippet
@Override
public int getItemViewType(int position) {
// Just as an example, return 0 or 2 depending on position
// Note that unlike in ListView adapters, types don't have to be contiguous
return position % 2 * 2;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: return new ViewHolder0(...);
case 2: return new ViewHolder2(...);
...
}
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolder0 viewHolder0 = (ViewHolder0)holder;
...
break;
case 2:
ViewHolder2 viewHolder2 = (ViewHolder2)holder;
...
break;
}
}
For more detaild please refer this link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With