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();
}
});
}
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.