Recyclerview.getLayoutPosition()问题

来源:互联网 发布:广州市软件创新人才 编辑:程序博客网 时间:2024/06/03 12:10

使用Recyclerview 时,如果要添加item的点击监听等功能,可以在Recyclerview.Adapter的onBindViewHolder中设置

例如:

@Overridepublic void onBindViewHolder(final MyViewHolder holder, int position) {    holder.tv.setHeight(150*(1+position%4));    holder.tv.setWidth(150*(1+position%4));    holder.tv.setText(data.get(position));    if(mOnItemClickListener!=null){        holder.tv.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                int pos=holder.getLayoutPosition();                mOnItemClickListener.onItemClick(v,pos);            }        });        holder.tv.setOnLongClickListener(new View.OnLongClickListener() {            @Override            public boolean onLongClick(View v) {                int pos=holder.getLayoutPosition();                mOnItemClickListener.onItemLongClick(v,pos);                return false;            }        });    }}
注意这里使用了ViewHolder的getLayoutPosition方法,此方法返回的pos值与onBindViewHolder方法传入的position值有可能不同。

根据SDK中的解释,在Recyclerview 进行添加、移除item等操作时,position位置可能会变化,而所有的adapter的刷新并不总是及时的,只有这个方法返回的才是当前item经过一些变换后所处的真正位置。

/** * Returns the position of the ViewHolder in terms of the latest layout pass. * <p> * This position is mostly used by RecyclerView components to be consistent while * RecyclerView lazily processes adapter updates. * <p> * For performance and animation reasons, RecyclerView batches all adapter updates until the * next layout pass. This may cause mismatches between the Adapter position of the item and * the position it had in the latest layout calculations. * <p> * LayoutManagers should always call this method while doing calculations based on item * positions. All methods in {@link RecyclerView.LayoutManager}, {@link RecyclerView.State}, * {@link RecyclerView.Recycler} that receive a position expect it to be the layout position * of the item.

另参考:http://stackoverflow.com/questions/29684154/recyclerview-viewholder-getlayoutposition-vs-getadapterposition

2 0