Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paging library - one recycler with multiple view types

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?

like image 233
Tom Wayne Avatar asked Aug 06 '18 08:08

Tom Wayne


People also ask

What is viewType in onCreateViewHolder?

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.


2 Answers

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.

like image 72
dilix Avatar answered Oct 16 '22 11:10

dilix


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.

like image 23
Chirag Solanki Avatar answered Oct 16 '22 10:10

Chirag Solanki