Recyclerview.getLayoutPosition()問題

使用Recyclerview 時,如果要添加item的點擊監聽等功能,可以在Recyclerview.Adapter的onBindViewHolder中設置

例如:

@Override
public 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

發佈了456 篇原創文章 · 獲贊 19 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章