简体   繁体   中英

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?

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.

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.

I wanted to add header to recyclerView. Couldn't have different item type for first position, as library after reloading items caused recyclerview to scroll all way down to bottom of list.

I have created ViewHolder that holds my regular list item plus my header. This way my regular item was on position 0 with header, library stopped scrolling to bottom of recyclerView as first item was pagination's item aswell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM