How to create a RecyclerView in Android?

top banner

How to create a RecyclerView in Android?

RecyclerView is one of the most powerful and flexible view widgets in Android. It is used to display a collection of data elements in a scrollable list, similar to ListView or GridView. However, RecyclerView provides several performance improvements and additional features over these older widgets.
RecyclerView allows you to display a large dataset in a limited amount of space by recycling and reusing the same views as the user scrolls through the list. This recycling mechanism reduces the number of view objects that need to be created and destroyed and improves the performance of the app. RecyclerView is highly customizable and can be configured to display data in different layouts, such as linear, grid, and staggered grid layouts. It also provides several built-in animations and touch feedback effects, making the user experience more engaging.
In this tutorial, we will learn how to create a RecyclerView in Android using Kotlin. We will cover the following topics:

  1. Add RecyclerView dependency to your app
  2. Define RecyclerView in your layout XML file
  3. Create a custom layout for each item in the list
  4. Create a custom ViewHolder class
  5. Create a custom adapter class
  6. Bind data to views using the adapter
  7. Set the adapter to the RecyclerView in the activity or fragment
  8. Implement onClickListener for RecyclerView items

So, let’s get started.
1. Add RecyclerView dependency to your app
First, you need to add the RecyclerView dependency to your app’s build.gradle file.

dependencies { implementation 'androidx.recyclerview:recyclerview:1.2.1' } 

2. Define RecyclerView in your layout XML file
Next, you need to define the RecyclerView in your layout XML file.

<androidx.recyclerview.widget.RecyclerView
 android:id="@+id/recycler_view"
 android:layout_width="match_parent"
 android:layout_height="match_parent" /> 

3. Create a custom layout for each item in the list
You need to create a custom layout for each item in the list. This layout will be used by the adapter to inflate views for each item in the list. The layout can be as simple or as complex as you need it to be.

<!-- list_item.xml -->
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">
 <ImageView
 android:id="@+id/item_image"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:src="@drawable/ic_launcher_foreground" />
 <TextView
 android:id="@+id/item_title"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginStart="16dp"
 android:gravity="center_vertical"
 android:textAppearance="?attr/textAppearanceListItem" /> 
</LinearLayout> 

4. Create a custom ViewHolder class
You need to create a custom ViewHolder class that will hold references to the views in the layout. The ViewHolder class is responsible for binding the data to the views.

class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
 {
 private val itemImage: ImageView = itemView.findViewById(R.id.item_image)
 private val itemTitle: TextView = itemView.findViewById(R.id.item_title) fun bind(item: Item)
 {
 itemImage.setImageResource(item.imageResourceId)
 itemTitle.text = item.title
 }
 } 

5. Create a custom adapter class
You need to create a custom adapter class that extends the RecyclerView.Adapter class. The adapter is responsible for creating views for each item in the list and binding data to those views.

class ItemAdapter(private val itemList: List<Item>) : RecyclerView.Adapter<ItemViewHolder>()
 {
 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
 val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.list_item, parent, false)
 return ItemViewHolder(itemView)
 }
 override
 fun onBindViewHolder(holder: ItemViewHolder, position: Int)
 {
 holder.bind(itemList[position])
 }
 override
 fun getItemCount() = itemList.size
 } 

The ItemAdapter takes a list of items in its constructor and extends the RecyclerView.Adapter class. It also overrides three methods:

  • onCreateViewHolder(): This method is responsible for creating a new view holder for each item in the list. It inflates the list_item layout and returns a new ItemViewHolder object.
  • onBindViewHolder(): This method is responsible for binding the data to the views. It gets the item at the specified position from the itemList and calls the bind() method on the ItemViewHolder to set the values of the views.
  • getItemCount(): This method returns the number of items in the list.

6. Bind data to views using the adapter
To bind data to views using the adapter, you need to create an instance of the ItemAdapter class and set it to the RecyclerView.

val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
 val itemAdapter = ItemAdapter(itemList) recyclerView.adapter = itemAdapter 

In this example, we create a new instance of the ItemAdapter class and pass the itemList to its constructor. Then, we set the adapter to the RecyclerView using the setAdapter() method.
7. Set the adapter to the RecyclerView in the activity or fragment
To display the RecyclerView in your activity or fragment, you need to set the adapter to the RecyclerView and set the layout manager.

val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
 val itemAdapter = ItemAdapter(itemList)
 recyclerView.adapter = itemAdapter
 recyclerView.layoutManager = LinearLayoutManager(this) 

In this example, we set the adapter and layout manager for the RecyclerView. We use the LinearLayoutManager to display the items in a vertical list. You can also use GridLayoutManager or StaggeredGridLayoutManager to display items in a grid or staggered grid layout.
8. Implement onClickListener for RecyclerView items
To handle clicks on the items in the RecyclerView, you need to implement an OnClickListener for the views in the ItemViewHolder class.

class MainActivity : AppCompatActivity(), ItemViewHolder.OnItemClickListener
 {
 override
 fun onCreate(savedInstanceState: Bundle?)
 {
 super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
 val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
 val itemAdapter = ItemAdapter(itemList, this)
 recyclerView.adapter = itemAdapter
 recyclerView.layoutManager = LinearLayoutManager(this)
 }
 override
 fun onItemClick(position: Int)
 {
 // Handle item click here 
}
 } 

In this example, we define an interface OnItemClickListener that has a single method onItemClick(). The ItemViewHolder class implements the OnClickListener interface and calls the onItemClick() method when the view is clicked. We also pass the listener to the constructor of the ItemViewHolder class, so that we can handle clicks in the activity or fragment that uses the RecyclerView.
To handle clicks in the activity or fragment that uses the RecyclerView, you need to implement the OnItemClickListener interface in the activity or fragment and set it to the adapter.

class MainActivity : AppCompatActivity(), ItemViewHolder.OnItemClickListener
 {
 override
 fun onCreate(savedInstanceState: Bundle?)
 {
 super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
 val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
 val itemAdapter = ItemAdapter(itemList, this) recyclerView.adapter = itemAdapter recyclerView.layoutManager = LinearLayoutManager(this)
 }
 override
 fun onItemClick(position: Int)
 {
 // Handle item click here 
} 
} 

In this example, we implement the OnItemClickListener interface in the MainActivity and pass it to the constructor of the ItemAdapter. Then, we set the adapter to the RecyclerView in the onCreate() method of the activity. When an item is clicked, the onItemClick() method is called in the MainActivity, and we can handle the click event there.
That’s it! You have successfully created a RecyclerView in your Android app and implemented a custom adapter class with click handling. You can now display a list of items in your app and handle clicks on the items.

Conclusion

The RecyclerView is a powerful and flexible widget that allows you to display large lists of items in your Android app efficiently. In this tutorial, we have covered how to create a RecyclerView, create a custom adapter class, and handle clicks on the items in the RecyclerView. We hope you found this tutorial helpful and that you can use it as a starting point for your own RecyclerView implementation.

Leave a Reply

Your email address will not be published. Required fields are marked *