Android SectionedRecyclerViewAdapter 实现 getItemId

Android SectionedRecyclerViewAdapter implement getItemId

我正在使用 luizgrp/SectionedRecyclerViewAdapter 中的 SectionedRecyclerViewAdapter 作为我的 RecyclerView 的适配器。

使用 RecyclerViewAdapter,如果我想唯一标识每一行,我将覆盖此方法:

@Override
public long getItemId( int position ) {
    return this.dataList.get(position).getId();
}

但是我如何用 SectionedRecyclerViewAdapter 做到这一点?我有如下部分代码,我添加了 getId() 方法:

public class Section1 extends Section {
      .....

      public long getItemId(int position) {
        if (position == 0) {
          return 0;
        }

        return this.openPosList.get(position - 1).getId();
      }
}

我想我应该扩展 SectionedRecyclerViewAdapter 并覆盖 getItemId()。但是我在将 position 转换为 Section 的行位置时遇到问题。

public class PositionRecylerViewAdapter extends SectionedRecyclerViewAdapter {
     ......

     @Override
     public long getItemId(int position) {
           //  ????
           // transform position here into Section's item position, considering multiple Sections with Header & Footer
           //  ????
     }

}

有人用任何示例代码实现过类似的代码吗?谢谢!

我想出来并在我的 PositionRecylerViewAdapter 中实现了它。

public class PositionRecyclerViewAdapter extends SectionedRecyclerViewAdapter {

    public PositionRecyclerViewAdapter() {
        super();
        ......

        this.setHasStableIds(true);
    }

    .......

    @Override
    public long getItemId (int index) {
        int viewType = this.getSectionItemViewType(index);
        Section1 section1 = (Section1) this.getSection(POSITION_SECTION);

        if (viewType == SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER) {
            return section1.getHeaderId();
        } else if (viewType == SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED) {
            int sectionItemIndex = this.getPositionInSection(index);
            return section1.getItemId(sectionItemIndex);
        }

        return -1;
    }

}

Section1 class:

public class Section1 extends Section {
    .....

    public long getHeaderId() {
        return headerId;
    }

    public long getItemId(int index) {
        return this.openPosList.get(index).getId();
    }
}

发布了我自己的答案,希望下次有人觉得它有用,谢谢!