Android SectionedRecyclerViewAdapter implement getItemId

800 Views Asked by At

I am using SectionedRecyclerViewAdapter from luizgrp/SectionedRecyclerViewAdapter as adapter for my RecyclerView.

With RecyclerViewAdapter, if I want to uniquely identify each row, I will override this method:

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

But how do I do that with SectionedRecyclerViewAdapter? I have Section code as below, I added getId() method:

public class Section1 extends Section {
      .....

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

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

I think I shall extends SectionedRecyclerViewAdapter & override getItemId(). But I have problem converting the position into Section's row position here.

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
           //  ????
     }

}

Anyone implement similar code before, with any sample code? Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

I figure it out & implement this in my 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;
    }

}

In Section1 class:

public class Section1 extends Section {
    .....

    public long getHeaderId() {
        return headerId;
    }

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

Posted my own answer & hopefully someone finds it useful next time, thanks!