In tutorials on internet where they setOnClickListener in Adapter of RecyclerView they define it in two ways : either inside ViewHolder or inside BindViewHolder.
My Question is which one is a better approach, Please recommend any another approach if available
1) inside ViewHolder:
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
tvSrc = (TextView) itemView.findViewById(R.id.tvSrc);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "inside viewholder position = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
}
2) inside BindViewHolder
public void onBindViewHolder(DisplayTrainsAdapter.ViewHolder viewHolder, final int position) {
viewHolder.tvSrc.setText(mDataset.get(position).strSrc);
viewHolder.tvSrc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position = " + getItemId(position), Toast.LENGTH_SHORT).show();
}
});
}
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 calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView. Returns the position of the given ViewHolder in the given Adapter . Returns the total number of items in the data set held by the adapter. Return the stable ID for the item at position .
Your number 1 solution is the best as you proposed since that assignment will not be called in the Binding at each invalidate triggered by notify..() methods. I know also others solutions but you need to implement android.view.GestureDetector in your activity.
If you want others improvements on the adapter, take a look at mine FlexibleAdapter https://github.com/davideas/FlexibleAdapter and feel free to implement in your project.
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