Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement subheaders/sections inside a RecyclerView?

I am trying to implement subheaders inside my RecyclerView. As the adapter for my RecyclerView, I am using the PagedListAdapter from the brand new Paging Library with the combination of Room.

The data coming from the database contains dates. I want to separate/group the items by day and show the date inside the subheader.

What would be the best way to implement subheaders with this combination? AFAIK it is impossible to implement this the 'standard' ViewType way, because that would replace the first data list item with the header. At this moment I am trying to accomplish it with RecyclerView.ItemDecoration, but I am not able to make it work.

Can anyone point me in the right direction?

So far my RecyclerView.ItemDecoration:

public class RecyclerViewHeaderItemDecoration extends RecyclerView.ItemDecoration {

private RecyclerViewHeaderReceiver receiver;

public RecyclerViewHeaderItemDecoration setReceiver(RecyclerViewHeaderReceiver receiver) {
    this.receiver = receiver;
    return this;

}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {

    final int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        if (receiver != null) {
            View view = parent.getChildAt(i);
            int position = parent.getChildAdapterPosition(view);
            int previousPosition = position - 1;
            if (position == 0 || (position != RecyclerView.NO_POSITION && receiver.isNewSection(previousPosition, position))) {
                ViewHolder headerView = receiver.getSectionHeaderViewHolder(position);
                parent.getAdapter().bindViewHolder(headerView, position); // I was not able to 'insert' a new viewHolder
            }
        }
    }
}

public interface RecyclerViewHeaderReceiver {
    boolean isNewSection(int prevPosition, int position);
    ViewHolder getSectionHeaderViewHolder(int position);
}
 }
like image 903
tomwassing Avatar asked Oct 03 '17 22:10

tomwassing


1 Answers

so I was solving the same problem as you recently and I managed to accomplish it with this library

https://github.com/edubarr/header-decor

It uses the ItemDecoration approach you have been trying.

like image 86
filipproch Avatar answered Sep 17 '22 19:09

filipproch