Search code examples
javaandroidandroid-recyclerviewandroid-viewholder

Where should I place setOnClickListener in a RecyclerView Adapter


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

Solution

  • Both options have their pros and cons.

    For example, if a Button is clicked and you want to change the text of your button, then you should probably use the option where you setup the onClick listener in the ViewHolder. Apart from this reason, it also makes your code look cleaner.

    However, if say, when the Button is clicked, you want to change the text of a TextView in the same index/position as the button that was clicked, you will need to use the option where you setup the onClick listener in the onBindViewHolder method.