在许多问题中,人们说“在oncreateviewholder中调用onclicklistener”。不需要调用onClickListener onBindViewHolder中的每个项”
@Override
public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
final ViewHolder holder = new ViewHolder(v);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "position = " + holder.getAdapterPosition());
}
});
return new Viewholder(v);
}
@Override
public void onBindViewHolder(final BoardListViewHolder holder, int position) {
}
但在logcat中,总是显示“position=-1”
这是不对的。
为什么我要在oncreateviewholder中调用onclicklistener?
最佳答案
onCreateViewHolder中的getAdapterPosition始终为“-1”
你应该return holder
而不是new Viewholder(v)
。
代码结构
@Override
public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
final ViewHolder holder = new ViewHolder(v);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "position = " + holder.getAdapterPosition());
}
});
return holder;
}
@Override
public void onBindViewHolder(final BoardListViewHolder holder, int position) {
}