如何在RecyclerView中实现subheaders / sections?

时间:2017-10-03 22:28:28

标签: android android-room

我正在尝试在RecyclerView内实施subheaders。作为RecyclerView的适配器,我使用全新PagedListAdapter中的Paging LibraryRoom的组合。

来自数据库的数据包含日期。我希望按日分隔/分组项目并在子标题内显示日期。

使用此组合实施subheaders的最佳方法是什么? AFAIK无法实现这种“标准”ViewType方式,因为这将用标头替换第一个数据列表项。此刻我正试图用RecyclerView.ItemDecoration来完成它,但我无法使它工作。

有人能指出我正确的方向吗?

到目前为止我的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);
}
 }

1 个答案:

答案 0 :(得分:1)

所以我最近解决了和你一样的问题,我设法用这个库来完成它

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

它使用您一直在尝试的ItemDecoration方法。