Android RecyclerView with OnItemClickListener

In this tutorial we are going to learn how to implement Android RecyclerView with OnItemClickListener. Our output will be application showing a list of fruit images, fruit name and fruit description which in this case it’s the scientific name of that fruit as shown in the image below. When the item in the RecyclerView is clicked a toast will appear with the name of that clicked item.

Android RecyclerView with OnItemClickListener

  • Create another Layout Resource file for holding RecyclerView data.
  • Right click layout => New => Layout Resource File and name it fruits_list_data.
  • Copy and Paste the code below to your fruits_list_data file.
  • Preview of fruits_list_data is shown below.
  • RecyclerView Component

    Adding fruit images

  • Download fruit images by clicking the link below.
  • Unzip copy and paste the image in the drawable folder.
  • Download fruit images

    Creating Model class

  • Create a new java class and name it Fruits, This class will be used for storing and getting our RecyclerView Items.
  • Copy and Paste the code below in Fruits.java class
  • Creating RecyclerView Adapter

  • Create a new class and name it FruitAdapter.
  • This class extends RecyclerView Adapter and also manages and displays our data.
  • This class have 3 method.
  • The first method is onCreateViewHolder which typically set the view which is used to display data.
  • The second method is onBindViewHolder which needs to fetch appropriate data and use it to fill the view holder layout.
  • The third method is getItemCount which return the size the of the items.
  • Copy and Paste the code below inside your FruitAdapter class .
  • Now we need to set this Adapter to our recyclerView that we had created.
  • Set FruitAdapter to recyclerView

  • Open your MainActivity class.
  • Copy and Paste the code below in your MainActivity.java file.
  • The code will set our FruitAdapter to recyclerView and also set OnItemClickListener.
  • Finally Create FruitTouchListener class that will enable us to perform some actions when an item is clicked.
  • Creating FruitTouchListener

  • Create a class and name it FruitTouchListener.
  • Copy and paste the code below in it.
  • Now try and run your app, You will get the output below.
  • Android RecyclerView with OnItemClickListener

  • To download the source code click here .
  • That’s all if you have any question or need help do comment below