Kahibaro
Discord Login Register

13.1 RecyclerView Basics

Understanding RecyclerView

RecyclerView is the standard Android component for displaying a scrollable list or grid of items. It replaces the older ListView and GridView widgets and gives you more control over how items are displayed and reused.

At its core, RecyclerView shows a collection of views on the screen and automatically recycles off-screen views for new data. This approach improves performance and reduces memory usage when dealing with long lists.

You will typically use RecyclerView when you need to show any repeating content, such as a list of messages, products, contacts, or news articles.

Important rule: Always use RecyclerView for modern list or grid interfaces. ListView is considered legacy and should be avoided in new Android apps.

Key Components of RecyclerView

RecyclerView itself is only a container that knows how to show a scrolling list and recycle its children. It does not know how to create individual row views or how to display data. That work is delegated to three main components: the layout manager, the adapter, and the view holder.

The layout manager controls how list items are arranged. You will usually use LinearLayoutManager for vertical or horizontal lists, GridLayoutManager for grids, or StaggeredGridLayoutManager for more complex layouts. RecyclerView cannot work without a layout manager, so you must always set one.

The adapter provides the data for the list. It knows how many items you have and how to bind each piece of data to a view. You will implement your own adapter by extending RecyclerView.Adapter.

The view holder describes each item view and holds references to its inner views. This pattern avoids calling findViewById repeatedly, which improves performance. You will create a custom class that extends RecyclerView.ViewHolder inside your adapter.

Basic Setup in XML

To use RecyclerView, you first add it to your layout XML file. The RecyclerView widget is part of the AndroidX library, so you use the androidx.recyclerview.widget.RecyclerView class.

A simple layout with a full-screen vertical list can look like this:

<androidx.recyclerview.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

In more complex screens, the RecyclerView can be one of many views, such as inside a ConstraintLayout or below a toolbar. The important point is that it behaves like any other View in XML, with id, layout_width, and layout_height attributes.

Setting Up RecyclerView in an Activity

Once the RecyclerView is added to your layout, you interact with it in your activity or fragment. You must typically do three things: find the RecyclerView by its id, set a layout manager, and set an adapter.

The layout manager decides whether your items are vertical, horizontal, or in a grid. The simplest case is a vertical list using LinearLayoutManager.

A basic setup in an activity might look like this:

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: MyAdapter  // You will define this class
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        val items = listOf("Apple", "Banana", "Orange")
        adapter = MyAdapter(items)
        recyclerView.adapter = adapter
    }
}

In this example, the LinearLayoutManager creates a simple vertical list. If you wanted a horizontal list, you would pass LinearLayoutManager.HORIZONTAL as a second argument, and for a grid you would use GridLayoutManager instead.

Role of the Adapter and ViewHolder

The adapter connects your data to the RecyclerView. It knows how to create new item views when needed and how to reuse existing ones. This is where the view holder plays a crucial role.

The adapter has three essential responsibilities. It must know how many items to display, through getItemCount. It must create a new view holder when RecyclerView needs a new row, through onCreateViewHolder. It must bind data to an existing view holder when it should display a specific item, through onBindViewHolder.

The view holder holds the reference to the views that make up a single row or cell of the list. By keeping these references, RecyclerView can quickly update content when you scroll, without recreating views or searching the view hierarchy.

Although you will implement adapters and view holders in detail later, visually you can think of them as isolated units. Each unit describes one item, such as a single contact row with a name, an avatar, and a phone number.

Important statement: The RecyclerView adapter must always return the correct item count and must never modify the list while it is iterating through items without notifying the adapter, or you can cause crashes.

Inflating Item Layouts

Each item in the RecyclerView is defined by a separate XML layout. This XML represents the structure of a single row, like a TextView-only row for a simple string list, or a more complex layout with images and multiple text fields.

In onCreateViewHolder, the adapter inflates this item layout. Inflating means converting the XML description into an actual View object. The layout is not attached to the parent immediately, so you pass false for the attachToRoot parameter.

A typical inflation step looks like this inside the adapter:

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

The parent parameter is the RecyclerView itself. Passing it to inflate helps Android calculate correct layout parameters, for example width set to match_parent.

Recycling and Performance

The main power of RecyclerView comes from its recycling behavior. Instead of creating a new view for every item in your dataset, RecyclerView creates only enough views to fill the screen plus a few extra for smooth scrolling. When an item scrolls off-screen, its view is kept and reused for the new item that is about to appear.

This process depends on the view holder pattern. Once a view holder is created, it is reused many times for different data items. In onBindViewHolder, you update the content of the existing views to match the data at a new position.

This recycling approach leads to better memory usage and smoother scrolling, especially for large lists. You must be careful to always fully update the view in onBindViewHolder and not rely on any previous state, because the same holder might have displayed completely different data before.

Important rule: In onBindViewHolder, always set all the visible state for the item. Never assume the view is in a default state, because recycled views may contain old content.

Basic Layout Managers

RecyclerView does not make any assumptions about the way items are positioned. Layout managers handle this responsibility. You will primarily use three built-in layout managers.

LinearLayoutManager arranges items in a single row or column. For a standard vertical list you use LinearLayoutManager(context). For a horizontal list you pass an orientation argument and specify that items should scroll horizontally.

GridLayoutManager arranges items in a grid with multiple columns or rows. You choose the number of spans, that is, the number of columns in a vertical grid or rows in a horizontal grid. This is useful for image galleries or product grids.

StaggeredGridLayoutManager allows items of varying sizes to be arranged in a staggered grid. This can create a Pinterest style layout where each item has a different height.

All layout managers are set through recyclerView.layoutManager = .... Changing the layout manager can completely change the visual arrangement of items without changing your data or adapter logic.

Handling Simple Data Changes

After the initial setup, you often need to update the list contents. For a basic implementation, you can replace the data list in your adapter and call notifyDataSetChanged() to inform RecyclerView that everything should be redrawn.

For example, you might have a function in your adapter that updates the items:

fun updateItems(newItems: List<String>) {
    items = newItems
    notifyDataSetChanged()
}

This approach is easy to understand and works for beginners, but it is not the most efficient for very large lists, because all visible items are rebound. Later you can improve this with more precise notification methods or utilities that calculate differences.

Summary of the RecyclerView Flow

When you combine these pieces, the basic flow of using RecyclerView is straightforward. You define a RecyclerView in XML. In your activity or fragment, you find it, set a layout manager, and provide an adapter. The adapter knows how to inflate item layouts, create view holders, and bind data. RecyclerView uses the layout manager to place views on screen and recycles view holders as you scroll.

Once this foundation is clear, you can extend RecyclerView with more advanced behaviors like custom item animations, click handling inside items, and pagination.

Views: 1

Comments

Please login to add a comment.

Don't have an account? Register now!