在写RecyclerViewAdapter中的onBindViewHolder方法中,需要传入position
因为其中istener内部类中要用到position,所以将position传入时就用final修饰,但是报错了
@Override
public void onBindViewHolder(@NonNull final CollectionViewHolder holder, final int position) {
if (listener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.itemClick(v, position);
}
});
}
}
final int position处飘黄:
Do not treat position as fixed; only use immediately and call holder.getAdapterPosition() to look it up later less... (Ctrl+F1)
RecyclerView will not call onBindViewHolder again when the position of the item changes in the data set unless the item itself is invalidated or the new position cannot be determined. For this reason, you should only use the position parameter while acquiring the related data item inside this method, and should not keep a copy of it. If you need the position of an item later on (e.g. in a click listener), use getAdapterPosition() which will have the updated adapter position.
Issue id: RecyclerView
所以不需要用final修饰position,只需要在需要position时调用holder.getAdapterPosition()方法即可:
listener.itemClick(v, holder.getAdapterPosition());
网友评论