Popular Searches
Popular Course Categories
Popular Courses

Using RecyclerView for Lists and Repeated UI Elements

Using RecyclerView for Lists and Repeated UI Elements

Android UI Development with XML Layouts

Using RecyclerView for Lists and Repeated UI Elements in Android

Course: Android App Development

Topic: Using RecyclerView for Lists and Repeated UI Elements

Course Link: Android App Development Course – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to RecyclerView

Android applications frequently display collections of similar items. Examples include contact lists, product catalogs, chat messages, news feeds, course listings, transaction histories, and search results. Each item may contain text, images, buttons, or other UI elements arranged in a repeated layout.

RecyclerView is an Android UI component designed to display and efficiently manage collections of data. It reuses item views as users scroll, reducing the need to create a separate view for every item in a large collection.

RecyclerView is part of AndroidX and provides flexibility for displaying items in vertical lists, horizontal lists, grids, and other arrangements through layout managers.

2. Learning Objectives

  • Understand RecyclerView and its role in Android applications.
  • Learn the difference between RecyclerView and ScrollView.
  • Understand Adapter, ViewHolder, and LayoutManager.
  • Create a RecyclerView using XML and Kotlin.
  • Display a collection of repeated UI elements.
  • Handle item clicks and update displayed data.
  • Use RecyclerView for lists, grids, and horizontal scrolling.
  • Understand performance, accessibility, and common troubleshooting techniques.

3. What Is RecyclerView?

RecyclerView is a ViewGroup that displays a collection of items using reusable item views. It separates the data, item presentation, and layout arrangement into different responsibilities.

For example, an application displaying 500 products does not need to keep 500 fully created item views on screen. RecyclerView can reuse views as items enter and leave the visible area.

Key Features of RecyclerView

  • View recycling: Reuses item views to reduce unnecessary view creation.
  • Flexible layouts: Supports vertical lists, horizontal lists, and grids.
  • Custom item designs: Allows each row to contain text, images, buttons, and other components.
  • Data-driven presentation: An Adapter connects the collection of data to item views.
  • Efficient updates: Supports targeted insertions, removals, moves, and content changes.
  • Scroll support: Provides scrolling for collections that extend beyond the visible area.

4. RecyclerView Architecture

A typical RecyclerView implementation uses three main components: Adapter, ViewHolder, and LayoutManager.

Data Collection
      |
      v
   Adapter
      |
      v
  ViewHolder
      |
      v
   Item Layout
      |
      v
 RecyclerView
      |
      v
 LayoutManager
(positions items)
Component Responsibility
RecyclerView Displays the collection and coordinates item presentation and scrolling.
Adapter Provides item counts, creates item holders, and binds data to them.
ViewHolder Holds references to the views belonging to an item.
LayoutManager Determines how items are positioned, such as vertically, horizontally, or in a grid.
Data source Contains the information displayed in the list.

5. Understanding the Adapter

The Adapter connects the data collection to RecyclerView. It tells RecyclerView how many items exist, creates ViewHolder instances, and binds the correct data to each item.

For example, a course application may store course names in a list. The Adapter takes a course name and displays it in the TextView belonging to the appropriate row.

A RecyclerView Adapter commonly implements three methods:

  • onCreateViewHolder() creates an item view and its ViewHolder.
  • onBindViewHolder() places the correct data into an existing ViewHolder.
  • getItemCount() returns the number of items in the data collection.

6. Understanding ViewHolder

A ViewHolder represents the views used by one RecyclerView item. It stores references to components such as TextView, ImageView, and Button so they can be reused when the item is displayed again.

Without an appropriate ViewHolder pattern, repeatedly looking up child views can add unnecessary work. RecyclerView's ViewHolder architecture helps make repeated item binding more efficient.

For example, a product ViewHolder might hold:

  • A TextView for the product name.
  • A TextView for the product price.
  • An ImageView for the product picture.
  • A Button for viewing details.

7. Understanding LayoutManager

The LayoutManager determines how RecyclerView arranges its items. The choice depends on the design and the type of information being displayed.

LayoutManager Purpose Example
LinearLayoutManager Displays items in a single vertical or horizontal direction. Contacts, messages, courses
GridLayoutManager Displays items in a grid with a specified number of spans. Photo galleries, product grids
StaggeredGridLayoutManager Supports grid layouts in which items may have different sizes. Masonry-style image collections

8. Setting Up RecyclerView in an Android Project

RecyclerView is provided by the AndroidX RecyclerView library. In a modern Android project, add the dependency to the module-level Gradle build file if it is not already available.

For a Kotlin DSL Gradle file, the dependency has this form:

dependencies {
    implementation("androidx.recyclerview:recyclerview:1.4.0")
}

Use a compatible stable version for your project's Android Gradle Plugin, SDK, and dependency setup. Sync the project after modifying the dependency file.

9. Creating the RecyclerView in XML

First, add a RecyclerView to the Activity layout. The following example uses a vertical list.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/courseRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp"
    android:clipToPadding="false"
    android:scrollbars="vertical" />

The RecyclerView fills the available parent area. The Adapter and LayoutManager will be configured in Kotlin.

10. Creating an Item Layout

Each repeated item can use a separate XML layout. This makes the item design reusable and easier to maintain.

item_course.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/courseNameText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold"
        android:text="Course Name" />

    <TextView
        android:id="@+id/courseDescriptionText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp"
        android:textSize="14sp"
        android:text="Course description" />

</LinearLayout>

This item contains two TextViews: one for the course name and another for its description. You can add images, ratings, prices, or action buttons as needed.

11. Creating a Data Model

A data model represents the information that each list item will display. Instead of storing unrelated values in separate lists, you can create a Kotlin data class that groups related properties into one object.

Course.kt

data class Course(
    val name: String,
    val description: String
)

Each Course object contains a name and a description. An application can create a list of these objects and pass it to the RecyclerView Adapter.

12. Creating the RecyclerView Adapter

The Adapter creates item views and binds each Course object to its corresponding ViewHolder. In this example, the Adapter also handles item clicks through a callback.

CourseAdapter.kt

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class CourseAdapter(
    private val courses: List<Course>,
    private val onCourseClick: (Course) -> Unit
) : RecyclerView.Adapter<CourseAdapter.CourseViewHolder>() {

    class CourseViewHolder(itemView: View) :
        RecyclerView.ViewHolder(itemView) {

        val nameText: TextView =
            itemView.findViewById(R.id.courseNameText)

        val descriptionText: TextView =
            itemView.findViewById(R.id.courseDescriptionText)
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): CourseViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_course, parent, false)

        return CourseViewHolder(view)
    }

    override fun onBindViewHolder(
        holder: CourseViewHolder,
        position: Int
    ) {
        val course = courses[position]

        holder.nameText.text = course.name
        holder.descriptionText.text = course.description

        holder.itemView.setOnClickListener {
            onCourseClick(course)
        }
    }

    override fun getItemCount(): Int = courses.size
}

Explanation of the Adapter Code

Code element Explanation
CourseAdapter Connects the list of Course objects to the item layout.
CourseViewHolder Stores references to the item layout's TextViews.
onCreateViewHolder() Inflates item_course.xml and creates a ViewHolder.
onBindViewHolder() Displays the name and description for the current item.
getItemCount() Returns the number of courses in the collection.
onCourseClick Passes the selected Course object to the supplied click callback.

The Adapter receives a read-only List reference in this example. If you need to add or remove items, you should update the collection through a suitable data-management approach and notify the Adapter correctly, or use a list-diffing approach such as ListAdapter.

13. Connecting RecyclerView in MainActivity

After creating the data model, item layout, and Adapter, configure the RecyclerView in your Activity.

MainActivity.kt

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val recyclerView =
            findViewById<RecyclerView>(R.id.courseRecyclerView)

        val courses = listOf(
            Course(
                "Android Development",
                "Build mobile applications using Kotlin."
            ),
            Course(
                "Core Java",
                "Learn object-oriented programming."
            ),
            Course(
                "Python Programming",
                "Practice Python syntax and application development."
            ),
            Course(
                "Web Development",
                "Learn how websites and web applications work."
            ),
            Course(
                "Data Analytics",
                "Explore data analysis and visualization."
            )
        )

        recyclerView.layoutManager =
            LinearLayoutManager(this)

        recyclerView.adapter = CourseAdapter(courses) { course ->
            Toast.makeText(
                this,
                "Selected: ${course.name}",
                Toast.LENGTH_SHORT
            ).show()
        }
    }
}

How This Implementation Works

  1. The Activity loads activity_main.xml.
  2. The RecyclerView is located using its resource ID.
  3. A list of Course objects is created.
  4. LinearLayoutManager arranges the items vertically.
  5. CourseAdapter connects the data to the item layout.
  6. RecyclerView requests ViewHolder objects as required.
  7. The Adapter binds each course's information to its item.
  8. When an item is tapped, a Toast displays the selected course name.

This example demonstrates the complete flow from a data collection to a scrollable list. In a larger application, the data might come from a database, repository, or remote API rather than being hardcoded.

14. Handling Item Clicks

Many lists need to respond when a user selects an item. For example, tapping a course might open its detail screen, tapping a product might display its specifications, or tapping a contact might open a profile.

One reusable approach is to pass a callback into the Adapter, as demonstrated in the previous example. The Adapter reports which item was selected, while the Activity or Fragment decides what action should happen.

Example: Open a Detail Screen

recyclerView.adapter = CourseAdapter(courses) { course ->
    val intent = Intent(this, CourseDetailActivity::class.java)

    intent.putExtra("COURSE_NAME", course.name)
    intent.putExtra("COURSE_DESCRIPTION", course.description)

    startActivity(intent)
}

Add the required Intent import and create CourseDetailActivity with its layout before using this example. Register the Activity in the manifest if it is not already registered. The receiving Activity can retrieve the values from the Intent extras.

Best practice: keep navigation logic outside the Adapter when possible. This makes the Adapter reusable across different screens and easier to test.

15. Displaying a List in Horizontal Orientation

RecyclerView can display items horizontally by using a horizontal LinearLayoutManager. This layout is useful for category selectors, featured products, recommended courses, and image carousels.

recyclerView.layoutManager = LinearLayoutManager(
    this,
    LinearLayoutManager.HORIZONTAL,
    false
)

For a horizontal list, the item layout should have an appropriate width, such as a fixed or constrained card width. A child item that always occupies the full available width may not produce the desired horizontal layout.

16. Displaying Items in a Grid

GridLayoutManager arranges items into rows and columns. It is useful when users need to view several items at once, such as in a gallery or product catalog.

recyclerView.layoutManager = GridLayoutManager(
    this,
    2
)

The second argument specifies the number of spans. In a vertical grid, it usually represents the number of columns. For a responsive grid, choose a span count appropriate for the available screen width.

17. Updating RecyclerView Data

List data may change while the application is running. For example, a user might add a course to a saved list, remove a task, or receive new messages.

RecyclerView must be informed when its displayed data changes. For a simple mutable list, Adapter notification methods can be used after updating the data correctly.

Example: Adding an Item

For this example, use a mutable list and an Adapter that references that same list.

val courses = mutableListOf(
    Course("Android Development", "Build Android apps."),
    Course("Kotlin Basics", "Learn Kotlin fundamentals.")
)

// After updating the list:
courses.add(
    Course("UI Design", "Create usable mobile interfaces.")
)

adapter.notifyItemInserted(courses.lastIndex)

The variable adapter represents the Adapter instance already attached to the RecyclerView. This example assumes the list is modified on the main thread and that the Adapter references the same mutable list.

Common Notification Methods

Method Purpose
notifyItemInserted(position) Reports that an item was inserted.
notifyItemRemoved(position) Reports that an item was removed.
notifyItemChanged(position) Reports that an item at a position changed.
notifyItemMoved(from, to) Reports that an item moved from one position to another.
notifyDataSetChanged() Reports that the entire dataset may have changed.

Use the most specific notification that correctly describes the update. Calling notifyDataSetChanged() for every small change can result in less efficient updates and less precise animations.

18. Using ListAdapter and DiffUtil

For applications that frequently receive new lists from a database or network, ListAdapter and DiffUtil can simplify updates. They compare the old and new lists and identify which items were inserted, removed, moved, or changed.

This approach is especially useful when a new immutable list is produced after a search, API response, or database update.

Example: Defining a DiffUtil Callback

class CourseDiffCallback : DiffUtil.ItemCallback<Course>() {

    override fun areItemsTheSame(
        oldItem: Course,
        newItem: Course
    ): Boolean {
        return oldItem.name == newItem.name
    }

    override fun areContentsTheSame(
        oldItem: Course,
        newItem: Course
    ): Boolean {
        return oldItem == newItem
    }
}

This simplified example treats the course name as the unique identifier. In a production application, a stable unique ID is usually better because names can change or may not be unique. The DiffUtil callback can then compare IDs for item identity and compare all relevant display properties for content equality.

19. RecyclerView Versus ScrollView

Both components can display scrollable content, but they are intended for different scenarios.

Feature RecyclerView ScrollView
Primary purpose Displaying collections of items Scrolling a single content area
View recycling Reuses item views through its Adapter and LayoutManager Does not automatically recycle arbitrary child views as a collection
Data binding Uses an Adapter and ViewHolder Content is usually defined directly in the child layout
Layout options Vertical, horizontal, grid, and custom arrangements Standard ScrollView scrolls vertically
Large repeated lists Generally the better choice Can become inefficient if all repeated items are created as child views
Typical examples Contacts, product lists, chat messages Long forms, articles, profile details

Use ScrollView when you need to scroll a relatively small, structured screen. Use RecyclerView when the screen primarily displays a collection of repeated items, especially if the collection is large or changes dynamically.

20. Common RecyclerView Errors and Solutions

Problem Possible Cause Solution
List appears empty The Adapter is missing, the dataset is empty, or the wrong layout is loaded. Verify the data, Adapter assignment, RecyclerView ID, and item layout.
Items show the same text The Adapter binds incorrect data or does not update every relevant view. Check the position and bind all item properties in onBindViewHolder().
LayoutManager error No LayoutManager has been assigned. Set a suitable LayoutManager before displaying the list.
Wrong item responds to a click Code relies on a stale position captured during binding. Use the bound item object or obtain a valid binding position when required.
New data is not visible The Adapter was not notified or a new list was not submitted. Use correct notification methods or ListAdapter.submitList().
Scrolling is slow Heavy binding work, oversized images, complex layouts, or excessive nested measurement. Simplify item layouts, optimize image loading, and move expensive work away from binding.
Images appear on the wrong rows Recycled ImageViews retain old content while binding is incomplete. Bind every image state correctly and use an image-loading library where appropriate.
Item spacing looks incorrect Margins or item decorations are not configured consistently. Review item dimensions and use a suitable RecyclerView.ItemDecoration when needed.

21. Performance Best Practices

  • Reuse views: Use ViewHolder to store references to item views.
  • Keep binding lightweight: Avoid expensive database calls, file operations, or network requests inside onBindViewHolder().
  • Optimize images: Load images at appropriate sizes and use an image-loading library for remote content.
  • Use stable identifiers where appropriate: A model with a unique ID makes item identity more reliable.
  • Update only what changed: Use targeted Adapter notifications or ListAdapter with DiffUtil.
  • Avoid unnecessary nesting: Keep item layouts simple and avoid complex hierarchies when possible.
  • Use the right layout manager: Select a linear list, grid, or custom layout based on the screen's needs.
  • Keep data work separate: Load data through a repository or other suitable data layer instead of fetching it during item binding.
  • Test scrolling: Check performance with realistic list sizes and on representative devices.

22. Accessibility and User Experience

A well-designed RecyclerView should be easy to navigate and understand for all users.

  • Use readable text sizes and sufficient contrast.
  • Give buttons and meaningful images accessible labels.
  • Ensure item click targets are large enough and clearly interactive.
  • Do not rely only on color to communicate item status.
  • Keep the focus order logical for keyboard and screen-reader navigation.
  • Provide useful empty, loading, and error states for data-driven lists.
  • Preserve scroll position when refreshing data where appropriate.
  • Test large fonts and different screen sizes.

23. Practical Project: Course Listing Application

Build a small Android application that displays a list of training courses. Each item should show a course name and description. Tapping a course should display the selected course name.

Project Requirements

  1. Create an Android Studio project using Kotlin.
  2. Add the RecyclerView dependency to the module-level Gradle file.
  3. Create activity_main.xml with a RecyclerView.
  4. Create item_course.xml for the repeated row layout.
  5. Create a Course data class with name and description properties.
  6. Create CourseAdapter with a ViewHolder and the required Adapter methods.
  7. Configure a LinearLayoutManager in MainActivity.
  8. Populate the list with at least ten course entries.
  9. Add a click callback for course selection.
  10. Test scrolling, item binding, and layout behavior on different screen sizes.

Possible Extensions

  • Add a search field to filter courses.
  • Display course images using ImageView.
  • Switch from a vertical list to a two-column grid.
  • Add a button to save or remove a course.
  • Load course data from a local database or API.
  • Use ListAdapter and DiffUtil for efficient list updates.
  • Add loading, empty, and error states.

24. Interview Questions and Answers

Q1. What is RecyclerView in Android?

Answer: RecyclerView is an AndroidX component used to display collections of items efficiently by reusing item views as they move on and off screen.

Q2. What is the purpose of an Adapter?

Answer: The Adapter connects a dataset to RecyclerView, creates ViewHolders, and binds the correct data to each item view.

Q3. What is a ViewHolder?

Answer: A ViewHolder stores references to the views used by an individual list item so they can be reused efficiently.

Q4. What does onCreateViewHolder() do?

Answer: It creates a new ViewHolder by inflating the item layout when RecyclerView needs another holder.

Q5. What does onBindViewHolder() do?

Answer: It binds the data for a particular item to the views held by the ViewHolder.

Q6. What does getItemCount() return?

Answer: It returns the number of items in the dataset that the Adapter currently represents.

Q7. Why is LayoutManager required?

Answer: It determines how items are positioned and arranged in the RecyclerView, such as in a vertical list or grid.

Q8. What is the difference between LinearLayoutManager and GridLayoutManager?

Answer: LinearLayoutManager arranges items in one direction, while GridLayoutManager arranges items in rows and columns.

Q9. Why is RecyclerView more suitable than ScrollView for long repeated lists?

Answer: RecyclerView reuses item views and provides Adapter-based collection handling, which is generally more efficient for large lists of repeated content.

Q10. How do you handle item clicks?

Answer: Register a click listener on the item view or a child control and pass the selected item to a callback or other application logic.

Q11. How do you add an item to RecyclerView?

Answer: Update the underlying dataset and notify the Adapter of the insertion, or submit a new list through ListAdapter.

Q12. What is DiffUtil?

Answer: DiffUtil calculates differences between two lists so the Adapter can update only the items that changed.

Q13. What causes repeated or incorrect item data?

Answer: Incorrect binding logic, stale state, or failing to reset all relevant views can cause recycled items to display incorrect information.

Q14. Can RecyclerView display a horizontal list?

Answer: Yes. Configure LinearLayoutManager with horizontal orientation.

Q15. Can RecyclerView display images and buttons?

Answer: Yes. Add ImageView, Button, TextView, or other components to the item layout and bind their content in the Adapter.

25. Quick Revision Checklist

  • RecyclerView is used for repeated and scrollable UI elements.
  • Adapter connects data to item views.
  • ViewHolder stores references to item views.
  • onCreateViewHolder() creates item holders.
  • onBindViewHolder() binds item data.
  • getItemCount() reports the number of items.
  • LayoutManager controls item arrangement.
  • LinearLayoutManager supports vertical and horizontal lists.
  • GridLayoutManager displays a grid.
  • Use appropriate notification methods or ListAdapter when data changes.
  • Use RecyclerView for large or dynamic repeated collections.
  • Keep item binding lightweight and test accessibility.

26. Conclusion

RecyclerView is an essential component for building efficient list-based interfaces in Android applications. Its Adapter, ViewHolder, and LayoutManager work together to connect data, create reusable item views, and arrange content on screen.

By learning how to create item layouts, bind data, handle clicks, configure vertical and horizontal lists, display grids, and update collections, developers can build practical interfaces for contacts, products, courses, messages, and other repeated UI elements.

For larger applications, combining RecyclerView with suitable data models, ListAdapter, DiffUtil, image-loading libraries, and a well-organized data layer helps keep the interface maintainable and responsive.


27. Useful Learning Resources

Previous Next
whatsapp