0

我使用SectionedRecyclerViewAdapterluizgrp/SectionedRecyclerViewAdapter作爲我的RecyclerView的適配器。Android SectionedRecyclerViewAdapter實現getItemId

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

} 

任何人都使用任何示例代碼實現類似的代碼?謝謝!

+0

所以你想調用該部分的getID()方法? – aborocz

+0

@aborocz是的,最終我將Section的getID() –

回答

0

我想出來&在我的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類:

public class Section1 extends Section { 
    ..... 

    public long getHeaderId() { 
     return headerId; 
    } 

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

發表我自己的答案&希望有人發現它有用的下一次,謝謝!