in many questions, people say "call OnClickListener in onCreateViewHolder. you don't need call OnClickListener each item in 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) {
}
but in Logcat, always show "position = -1"
this is not correct.
why i should call onClickListener in onCreateViewHolder?
getAdapterPosition in onCreateViewHolder is always “-1”
You should return holder
instead of new Viewholder(v)
.
Code Structure
@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) {
}
onCreateViewHolder
is used to inflate the layout resource only and you shouldn't put any methods related to your holder items here.
Instead, you have to use onBindViewHolder
to get the value of holder.getAdapterPosition
or set onClickListeners
etc. there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With