How to add Onclick listener to recycler view

You can handle this using two ways

1). Gesture touch https://www.google.co.in/amp/sapandiwakar.in/recycler-view-item-click-handler/amp/

2).Using interface in adapter https://antonioleiva.com/recyclerview-listener/

I suggest second way using interface

How to use interface for recycleritemclick

public class RecycleViewAdapter extends 
  RecyclerView.Adapter<RecycleViewHolder> {// Recyclerview will extend to
  private List<FileName> fileNames;
  private Context context;

//declare interface 
 private OnItemClicked onClick;

//make interface like this
    public interface OnItemClicked {
        void onItemClick(int position);
    }

  public RecycleViewAdapter(Context context,List<FileName> fileNames) {
    this.context = context;
    this.fileNames = fileNames;

Now assign click to interface

  @Override
    public void onBindViewHolder(RecycleViewHolder holder, final int position) {
        //............//
        holder.title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClick.onItemClick(position);
            }
        });

}

At the end of the adapter class up from finishing bracket make one method to assign itemclick to interface

public void setOnClick(OnItemClicked onClick)
{
    this.onClick=onClick;
}

In MainActivity.java Bind the item click with adapter

public class MainActivity extends Activity implements OnItemClicked {

    private RecyclerView mRecyclerView;
    private CityAdapter mAdapter;
    private List<City> cities;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city);

        mRecyclerView = (RecyclerView)findViewById(R.id.list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new CityAdapter(cities, R.layout.row_city, this);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnClick(MainActivity.this); // Bind the listener
    }

    @Override
    public void onItemClick(int position) {
        // The onClick implementation of the RecyclerView item click
    //ur intent code here
}

For Kotlin code please refer below link

How to handle recyclerview item click in kotlin?

Hope this help u if u need any help u can ask


Simplest solution would be to access the "itemView" public variable of holder class and set onClickListener on this.

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, NewActivity.class);
                intent.putExtra("FileName", list.get(position));
                context.startActivity(intent);
            }
        });        
}