The correct way of implementing getItemId() in RecyclerView.Adapter

半腔热情 提交于 2020-06-11 20:06:04

问题


I have generic class

public abstract class BaseAdapter<T> extends RecyclerView.Adapter {
  private List<T> itemsList = new ArrayList<>();
  //other override methods

  @Override
    public long getItemId(int position) {
        return position;
    }
}

What is the correct way to implementing getItemId()? I think that return position like in many example is not correct.


回答1:


  1. Create a base interface that has a method that returns a type long eg.

    interface BaseInterface{
        long getId(); 
    }
    
  2. Change

    abstract class BaseAdapter<T> extends RecyclerView.Adapter 
    

    to

    abstract class BaseAdapter<T extends BaseInterface> extends RecyclerView.Adapter {
    

    Note: The signature changed to T extends BaseInterface

  3. Replace

    @Override
    public long getItemId(int position) {
        return position;
    }
    

    with

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



回答2:


In the List you could only return the Id of the Item available at specific row as mentioned by Google documents:

getItemId

Get the row id associated with the specified position in the list.

But that's not the case with RecyclerView, in RecyclerView you have to ensure that you either return a unique Id for each Item or In case of no Stable Id you should return RecyclerView.NO_ID (-1). Please Refrain from returning values that are not stable. (An Stable value would be a unique value that does not change even if position of dataset changes)




回答3:


you should implement this methode: as you see you must tell the Adapter that you implemented that by setHasStableIds(true);

class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
MyAdapter() {
    setHasStableIds(true); // **very importent**
}

@Override
public long getItemId(int position) {
    // requires static value, it means need to keep the same value
    // even if the item position has been changed.
    return mItems.get(position).getId();
}

}



来源:https://stackoverflow.com/questions/42646950/the-correct-way-of-implementing-getitemid-in-recyclerview-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!