While i was looking at some tutorials about recycler view.some of them used the viewHolder constructor to attach the onClick listener while some of them used the onBindViewHolder method. which method is the best place to attach the onclicklistener. i'm really confused
Where do you add the android:onClick attribute to make items in a RecyclerView respond to clicks? In the layout file that displays the RecyclerView, add it to the element. Add it to the layout file for an item in the row.
This method internally calls onBindViewHolder to update the ViewHolder contents with the item at the given position and also sets up some private fields to be used by RecyclerView. This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView.
The method onBindViewHolder
is called every time when you bind your view with data. So there is not the best place to set click listener. You don't have to set OnClickListener
many times for the one View
. So the best solution is to set click listener in onCreateViewHolder
method. But the important thing is a how do you implement on click listener. If you for example want to get some model from list you can use getAdapterPosition()
method from ViewHolder
.
Look at the exmaple
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.view_magazine_list_item, null);
final ViewHolder result = new ViewHolder(view);
view.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
YourObject yourobject = yourObjectsList.get(result.getAdapterPosition()));
}
});
return result;
}
In ViewHolder
is the better place:
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//views declare here
public ItemViewHolder(View convertView)
{
super(convertView);
... ...
convertView.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
//do something to view here
//also you can get view position by 'getPosition()' here
}
}
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