Complete step-by-step guide: How to use RecyclerView on Android with examples and advanced customization

  • RecyclerView is the modern standard on Android for lists and grids, offering performance, flexibility, and maximum customization.
  • Its modular architecture allows you to define custom layouts, adapters, animations, and element types, adapting to any app need.
  • Its integration with other Jetpack libraries and best practices makes it easy to develop scalable, responsive, and visually compelling interfaces.

RecyclerView on Android

If you're an Android developer looking for an efficient and flexible way to display lists, grids, or large volumes of data in your app, RecyclerView is the modern and powerful solution you need to master. This versatile component of Android's Jetpack library has replaced ListView thanks to its customization options, improved performance, and modular architecture. Throughout this article, you'll learn step-by-step how to use RecyclerView, from initial setup to advanced customization techniques.

You'll find detailed explanations, professional tips, and practical examples in Kotlin and Java so you can implement any type of list or gallery in your projects. This article is designed for both those new to Android development and those looking to optimize their interfaces and take full advantage of RecyclerView's capabilities.

What is RecyclerView and why is it preferred over other alternatives?

RecyclerView Lifecycle

RecyclerView is an Android view component that allows you to display large datasets with minimal resource consumption by recycling and reusing views that are no longer visible on the screen, instead of creating new views each time. This optimizes memory usage and improves the user experience, enabling smooth lists and grids even with hundreds or thousands of items.

Compared with ListView, RecyclerView:

  • Divide functionality into small, reusable components (Adapter, ViewHolder, LayoutManager, ItemAnimator, ItemDecoration).
  • Allows greater customization of animations, decorations and item types (supports items with different layouts and behaviors in the same list).
  • Includes new APIs and better integration with other Jetpack and Material Design libraries.
  • Supports recommended architectural patterns such as ViewModel and LiveData for efficient lifecycle and data management.

Currently, RecyclerView is Google's recommended choice for implementing any list, gallery, grid, or carousel in Android applications.

Main components that make up a RecyclerView

To understand how it works, it is key to know the components that make it up and their role in the architecture:

  • RecyclerView: It is the container ViewGroup where the elements are rendered.
  • Adapter: Connects data to the RecyclerView, creates ViewHolders, and binds data to each view.
  • ViewHolder: Encapsulates individual views for each element and stores references to their components to improve performance and avoid repeated calls to findViewById.
  • LayoutManager: Controls how elements are arranged on the screen (linear, grid, etc.).
  • ItemAnimator: Allows you to animate changes such as insertions, deletions or updates to items.
  • ItemDecoration: Facilitates the addition of custom separators, margins, or decorations between elements.

This separation provides flexibility and makes the code easier to maintain and scale.

Why use RecyclerView? Key Benefits

Using RecyclerView brings key benefits to modern Android development:

  • Reusing views: The system recycles off-screen views instead of recreating them, optimizing memory and speed.
  • Design flexibility: Allows you to display items in vertical, horizontal, grid, Pinterest-style lists and more by simply changing the LayoutManager.
  • Support for multiple item types: You can display different layouts in the same list (banners, ads, products, titles, etc.) by implementing various types of ViewHolder.
  • Native and custom animations: Insert, delete or update items with fluid animations.
  • CardView and Material Design support: Ideal for creating visually appealing interfaces aligned with current recommendations.
  • Better integration with modern architectures and Jetpack Compose: Facilitates the adoption of patterns like MVVM and their use in conjunction with other Jetpack components.

How to configure RecyclerView in your Android project

Before you start using RecyclerView, it's important to prepare your project. You must include the necessary dependencies in your build.gradle file (module level):

implementation 'androidx.recyclerview:recyclerview:1.4.0'
implementation 'androidx.cardview:cardview:1.0.0'

Verify that you are using compatible versions of your minSdk and compileSdk . These dependencies will give you access to all RecyclerView and CardView components for your items.

How to declare a RecyclerView in XML

In the XML of the Activity or Fragment where you want to display the list, add the RecyclerView component as you would with any other view:

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

You can customize the width, height, padding, and other properties according to your design.

Define the layout of each list item

The appearance of each element is defined in a separate XML file (for example, item_product.xml ). It can be as simple as a single TextView, or as complex as a CardView with images, buttons, and other widgets.

Example layout using CardView and LinearLayout:

<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardElevation="4dp"
    card_view:cardCornerRadius="8dp"
    android:layout_margin="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <TextView
            android:id="@+id/textNombre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nombre del producto"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/textDescripcion"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Descripción breve" />

    </LinearLayout>

</androidx.cardview.widget.CardView>

This design can be adapted to any need by adding more views, images or buttons.

Creating the ViewHolder: Optimization and Modularity

The ViewHolder is a class that maintains references to the visual components of each element , avoiding repeated searches in the view tree and improving performance.

Example in Kotlin:

class ProductoViewHolder(view: View): RecyclerView.ViewHolder(view) {
    val nombre: TextView = view.findViewById(R.id.textNombre)
    val descripcion: TextView = view.findViewById(R.id.textDescripcion)
}

In modern versions, the use of ViewBinding or DataBinding is recommended for greater security and ease of access to views.

Creating the Adapter: The Bridge Between Data and Views

The Adapter is the heart of RecyclerView . Its function is to create and initialize the ViewHolders, and to link each data element to its corresponding position in the list.

class ProductosAdapter(private val lista: List<Producto>): RecyclerView.Adapter<ProductoViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_producto, parent, false)
        return ProductoViewHolder(view)
    }

    override fun getItemCount(): Int = lista.size

    override fun onBindViewHolder(holder: ProductoViewHolder, position: Int) {
        val producto = lista[position]
        holder.nombre.text = producto.nombre
        holder.descripcion.text = producto.descripcion
    }
}

The three methods you should always implement are:

  • onCreateViewHolder: Creates and inflates the layout of each item.
  • onBindViewHolder: Binds data to the views in the ViewHolder.
  • getItemCount: Indicates how many items the RecyclerView will display.

Configuring and initializing RecyclerView in the Activity or Fragment

Once the layouts, Adapter, and ViewHolder are defined, you must configure the RecyclerView in your Kotlin or Java code, usually in the onCreate method of the Activity:

val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(this) // Puedes cambiar por GridLayoutManager
recyclerView.adapter = ProductosAdapter(listaDeProductos)

The LayoutManager is essential for defining the arrangement of elements:

  • LinearLayoutManager: Vertical or horizontal list.
  • GridLayoutManager: Column/row grid.
  • StaggeredGridLayoutManager: Pinterest-like grid (elements of different sizes).

You can change the LayoutManager at runtime based on user action or app configuration.

Capturing events and interactions on elements

Detecting clicks on elements is essential for creating interactive lists. There are two common methods:

  1. From the Adapter: Assign a listener directly in the method onBindViewHolder (less recommended because it couples interface logic to the adapter).
  2. Through interfaces and callbacks: Create an interface to notify clicks and pass it to the Adapter from the Activity/Fragment. This is the most flexible and scalable way.

Example of interface in Kotlin:

interface OnProductoClickListener {
    fun onProductoClick(producto: Producto)
}

You can then pass an instance of this interface to the Adapter and call it when the click occurs.

Advanced customization techniques in RecyclerView

RecyclerView is designed to be highly customizable. Some advanced options include:

  • Handling multiple element types: Implement multiple layouts and ViewHolder to mix banners, ads, products and other types in the same list (using the method getItemViewType()).
  • Custom decorations: Uses ItemDecoration to add dividing lines, margins, graphic separators or backgrounds between items.
  • Animations: Customize animations when inserting, deleting, or updating items using ItemAnimator or integrates DiffUtil for efficient changes with animations.
  • Infinite scroll and progressive loading: Implement scroll listeners to load more data when reaching the end of the list.
  • Drag and drop: Allows you to easily rearrange list items using interactive user interfaces.
  • Swipe actions: Facilitates left/right drag gestures to delete, archive, or check items.

Is it mandatory to use CardView on each element?

No. Although it's common to combine RecyclerView with CardView to follow Material Design guidelines, you can use any type of container: LinearLayout, ConstraintLayout, FrameLayout, or even custom layouts.

The important thing is to define an XML file that matches the look and behavior you want for each item in your list.

RecyclerView News and Compatibility

The latest versions have added important improvements:

  • Optimization in complex animations.
  • Adaptive refresh rate support for fluid lists on modern devices.
  • Better interoperability with Jetpack Compose and other AndroidX libraries.
  • Extended support for ViewPager2 and other pagination views.

RecyclerView continues to receive updates and is compatible with a wide variety of Android versions, making it suitable for both new projects and migrations of existing apps.

Most common use cases for RecyclerView

The possibilities are virtually endless. Some common examples of use:

  • Contact lists, messages or chats.
  • Product grids in online stores.
  • Image or video galleries.
  • News listings, blogs, or dynamic posts.
  • Multimedia widgets, audio/video players, playlists.
  • Custom sections such as promotional banners, menus, calendars, etc.
  • Dynamic forms or step-by-step wizards.

You can even nest multiple RecyclerViews or combine them with other components to create highly complex and rich interfaces.

Best practices and recommendations for working with RecyclerView

When designing and scheduling listings with RecyclerView, consider the following tips:

  • Use ViewBinding o DataBinding to avoid errors and simplify access to views.
  • Upgrade only the necessary items using DiffUtil or the Adapter notification methods (notifyItemChanged, notifyItemInserted, etc.).
  • Avoid heavy or blocking operations within onBindViewHolderPrepare the data in advance.
  • For lists with multiple element types, implement getItemViewType() properly for efficient recycling.
  • Optimize images, especially in media playlists, using libraries like Glide or Picasso and asynchronous loading.
  • Only take advantage of animation and customization options when they add value to the user experience.
  • Consider accessibility and usability: Make sure elements are navigable, have adequate descriptions, and respond well to interactions.

RecyclerView Advanced Options and Little-Known Details

As you master RecyclerView, you can explore advanced features and patterns:

  • Adapter Delegates: Facilitates the management of multiple item types by delegating the responsibility of creating and linking each type to different classes.
  • Integration with LiveData and ViewModel: Allows the list to be automatically refreshed when data changes, facilitating reactive management in MVVM architectures.
  • Efficient pagination: Together with the Paging library, you can display infinite lists that load progressively from a database or remote API.
  • Integration with SwipeRefreshLayout: Adds support for reloading the list with a swipe down gesture.
  • testing: RecyclerView features specific utilities for UI testing, facilitating the automation and verification of the correct functioning of lists during development.

Additional resources, tips, and useful links about RecyclerView

To further expand your knowledge or review specific examples, you can review the following resources:

Mastering RecyclerView is one of the essential pillars of quality Android development. From basic listings to complex multimedia grids, this component allows you to create modern, fluid interfaces adapted to any need, always optimizing device resources and providing the best possible user experience.

Feel free to experiment, customize, and reuse the patterns presented here to take your Android apps to the next level.


Add as preferred source in Google