Reader small image

You're reading from  How to Build Android Apps with Kotlin

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781838984113
Edition1st Edition
Languages
Right arrow
Authors (4):
Alex Forrester
Alex Forrester
author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

Eran Boudjnah
Eran Boudjnah
author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

Alexandru Dumbravan
Alexandru Dumbravan
author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

Jomar Tigcal
Jomar Tigcal
author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal

View More author details
Right arrow

6. RecyclerView

Overview

In this chapter, you will learn how to add lists and grids of items to your apps and effectively leverage the recycling power of RecyclerView. You'll also learn how to handle user interaction with the item views on the screen and support different item view types—for example, for titles. Later in the chapter, you'll add and remove items dynamically.

By the end of the chapter, you will have the skills required to present your users with interactive lists of rich items.

Introduction

In the previous chapter, we learned how to fetch data, including lists of items and image URLs, from APIs, and how to load images from URLs. Combining that knowledge with the ability to display lists of items is the goal of this chapter.

Quite often, you will want to present your users with a list of items. For example, you might want to show them a list of pictures on their device, or let them select their country from a list of all countries. To do that, you would need to populate multiple views, all sharing the same layout but presenting different content.

Historically, this was achieved by using ListView or GridView. While both are still viable options, they do not offer the robustness and flexibility of RecyclerView. For example, they do not support large datasets well, they do not support horizontal scrolling, and they do not offer rich divider customization. Customizing the divider between items in RecyclerView can be easily achieved using RecyclerView.ItemDecorator...

Adding RecyclerView to Our Layout

In Chapter 3, Screens and UI, we saw how we can add views to our layouts to be inflated by activities, fragments, or custom views. RecyclerView is just another such view. To add it to our layout, we need to add the following tag to our layout:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/item_sample" />

You should already be able to recognize the android:id attribute, as well as the android:layout_width and android:layout_height ones.

We can use the optional tools:listitem attribute to tell Android Studio which layout to inflate as a list item in our preview toolbar. This will give us an idea of how RecyclerView might look in our app.

Adding a RecyclerView tag to our layout...

Populating the RecyclerView

So, we added RecyclerView to our layout. For us to benefit from RecyclerView, we need to add content to it. Let's see how we go about doing that.

As we mentioned before, to add content to our RecyclerView, we would need to implement an adapter. An adapter binds our data to child views. In simpler terms, this means it tells RecyclerView how to plug data into views designed to present that data.

For example, let's say we want to present a list of employees.

First, we need to design our UI model. This will be a data object holding all the information needed by our view to present a single employee. Because this is a UI model, one convention is to suffix its name with UiModel:

data class EmployeeUiModel(
    val name: String,
    val biography: String,
    val role: EmployeeRole,
    val gender: Gender,
    val imageUrl: String
)

We will...

Responding to Clicks in RecyclerView

What if we want to let our users select an item from the presented list? To achieve that, we need to communicate clicks back to our app.

The first step in implementing click interaction is to capture clicks on items at the ViewHolder level.

To maintain separation between our view holder and the adapter, we define a nested OnClickListener interface in our view holder. We choose to define the interface within the view holder because they are tightly coupled. The interface will, in our case, have only one function. The purpose of this function is to inform the owner of the view holder about the clicks. The owner of a view holder is usually a Fragment or an Activity. Since we know that a view holder can be reused, we know that it can be challenging to define it at construction time in a way that would tell us which item was clicked (since that item will change over time with reuse). We work around that by passing the currently presented item back...

Supporting Different Item Types

In the previous sections, we learned how to handle a list of items of a single type (in our case, all our items were CatUiModel). What happens if you want to support more than one type of item? A good example of this would be having group titles within our list.

Let's say that instead of getting a list of cats, we instead get a list containing happy cats and sad cats. Each of the two groups of cats is preceded by a title of the corresponding group. Instead of a list of CatUiModel instances, our list would now contain ListItem instances. ListItem might look like this:

sealed class ListItem {
    data class Group(val name: String) : ListItem()
    data class Cat(val data: CatUiModel) : ListItem()
}

Our list of items may look like this:

listOf(
    ListItem.Group("Happy Cats"),
    ListItem.Cat(
        CatUiModel...

Swiping to Remove Items

In the previous sections, we learned how to present different view types. However, up until now, we have worked with a fixed list of items. What if you want to be able to remove items from the list? There are a few common mechanisms to achieve that—fixed delete buttons, swipe to delete, and long-click to select then a "click to delete" button, to name a few. In this section, we will focus on the "swipe to delete" approach.

Let's start by adding the deletion functionality to our adapter. To tell the adapter to remove an item, we need to indicate which item we want to remove. The simplest way to achieve this is by providing the position of the item. In our implementation, this will directly correlate to the position of the item in our listData list. So, our removeItem(Int) function should look like this:

fun removeItem(position: Int) {
    listData.removeAt(position)
 ...

Adding Items Interactively

We have just learned how to remove items interactively. What about adding new items? Let's look into it.

Similar to the way we implemented the removal of items, we start by adding a function to our adapter:

fun addItem(position: Int, item: ListItemUiModel) {
    listData.add(position, item)
    notifyItemInserted(position)
}

You will notice that the implementation is very similar to the removeItem(Int) function we implemented earlier. This time, we also receive an item to add and a position to add it. We then add it to our listData list and notify RecyclerView that we added an item in the requested position.

To trigger a call to addItem(Int, ListItemUiModel), we could add a button to our main activity layout. This button could be as follows:

<Button
    android:id="@+id/main_add_item_button"
    android:layout_width="match_parent"
 ...

Summary

In this chapter, we learned how to add RecyclerView to our project. We also learned how to add it to our layout and how to populate it with items. We went through adding different item types, which is particularly useful for titles. We covered interaction with RecyclerView: responding to clicks on individual items and responding to swipe gestures. Lastly, we learned how to dynamically add and remove items to and from RecyclerView. The world of RecyclerView is very rich, and we have only scratched the surface. Going further would be beyond the scope of this book. However, it is strongly recommended that you investigate it on your own so that you can have carousels, designed dividers, and fancier swipe effects in your apps. You could start your exploration here: https://awesomeopensource.com/projects/recyclerview-adapter.

In the next chapter, we will look into requesting special permissions on behalf of our app to enable performing certain tasks, such as accessing the user...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
How to Build Android Apps with Kotlin
Published in: Feb 2021Publisher: PacktISBN-13: 9781838984113
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Authors (4)

author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal