aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • DevOps
  • Programming

Getting To Know RecyclerView

  • aster.cloud
  • September 29, 2020
  • 5 minute read

<a class="cm gh hz ia ib ic" href="https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/RecyclerView" target="_blank" rel="noopener nofollow noreferrer">RecyclerView</a> is a powerful UI widget that allows you to display a list of data in a flexible manner. When I was learning about RecyclerView, I found there were a lot of resources on how to create a complex one but not that many about creating a simple one. While the pieces that make up RecyclerView may seem confusing at first, they are fairly straightforward once you understand them.

This blog post goes through the steps of creating a simple RecyclerView that displays the names of different types of flowers. Along the way, I will also break down the different pieces that a RecyclerView needs so you can try it in your own apps.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

RecyclerView? What? Why?

A RecyclerView is a container used to display a list or grid of data, like text or photos.

When a list scrolls, only a handful of views are actually displayed on the screen. When a view scrolls off screen, RecyclerView reuses it and fills it with new data. This makes your app more efficient both in time and space, because it recycles existing structures instead of constantly creating new ones.

Image for post

The pink cells represent the cells displayed on screen and the yellow cell shows how a view that is scrolled off screen is recycled into a new view.

Why should you use RecyclerView?

  • RecyclerView uses the ViewHolder pattern which improves performance by allowing access to item views without frequent calls to findViewById().
  • RecyclerView, uses <a class="cm gh hz ia ib ic" href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.LayoutManager" target="_blank" rel="noopener nofollow noreferrer">LayoutManager</a>s which support lists that can scroll vertically and horizontally, staggered lists, and grids. Custom LayoutManagers are also possible to create.
  • RecyclerView provides default item animations and a way to customize them.

Overall, RecyclerView is a powerful tool because it allows for flexibility and customization.

Implementing RecyclerView

This blog post will show how to implement a simple RecyclerView that displays the names of different types of flowers. The code below will be written in Kotlin but RecyclerView can also be used in Java.

Read More  Android Dev Summit 2019 | Shrinking Your App with R8

Image for post

To get started, create a project with the Empty Activity template in Android Studio. Give it a creative name and choose Kotlin as the project’s language.

Image for post

Next, import the most current dependency for RecyclerView into the app level build.gradle file.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->
   
implementation 'androidx.recyclerview:recyclerview:1.1.0'

 

RecyclerView Data

One of the most important parts of RecyclerView is the data that is displayed. In a more complex app, data would be retrieved from a database or from the network, but for simplicity this app uses strings from a resource file in this app.

In the strings.xml file, create a string array with the flowers to be displayed.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

<resources>
    <string name="app_name">RecyclerView Sample</string>

    <string-array name="flower_array">
        <item>Lily</item>
        <item>Poppy</item>
        <item>Sunflower</item>
        <item>Freesia</item>
        <item>Daisy</item>
        <item>Rose</item>
        <item>Daffodil</item>
        <item>Lavender</item>
        <item>Peony</item>
        <item>Lilac</item>
        <item>Dahlia</item>
        <item>Tulip</item>
        <item>Dandelion</item>
    </string-array>
</resources>

Next, create a class called Datasource and have it take in context. Create a function called getFlowerList() that returns the array of flower names.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class Datasource(val context: Context) {
    fun getFlowerList(): Array<String> {
        return context.resources.getStringArray(R.array.flower_array)
    }
}

In MainActivity.onCreate(), create a val called flowerList and set it equal to getFlowerList().

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
  val flowerList = Datasource(this).getFlowerList()
}

 

RecyclerView Layout

Next, replace the default TextView in the activity_main layout resource file with a RecyclerView and set the layoutManager as LinearLayoutManager. Using LinearLayoutManager means that the data is presented in a vertical or horizontal list (it is vertical by default).

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   xmlns:app="http://schemas.android.com/apk/res-auto">

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

 

Read More  Jetpack Compose: Debugging Recomposition

Item Layout

Image for post

The diagram above shows a RecyclerView which is made up of items that display data. In this case, the items that make up the RecyclerView contain names of flowers.

Create a new layout file named flower_item, which describes how an item in the list should be displayed. This layout is responsible for displaying a single flower name, so all that is needed is a TextView.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

   <TextView
       android:id="@+id/flower_text"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textSize="50dp" />
</FrameLayout>

 

Breaking down the adapter class

Next up is the real meat of RecyclerView, the <a class="cm gh hz ia ib ic" href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder" target="_blank" rel="noopener nofollow noreferrer">ViewHolder</a> and <a class="cm gh hz ia ib ic" href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter" target="_blank" rel="noopener nofollow noreferrer">Adapter</a> class. A <a class="cm gh hz ia ib ic" href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ViewHolder" target="_blank" rel="noopener nofollow noreferrer">ViewHolder</a> stores information about a single item view in the RecyclerView. The RecyclerView creates only as many ViewHolders as are needed to display on screen plus a few extra in a cache. The ViewHolders are “recycled” (repopulated with new data) as the user scrolls; existing items disappear on one end and new items appear on the other end. The Adapter class gets data from the datasource and passes it into the ViewHolder which updates the views it is holding. The graphic below shows how the RecyclerView, Adapter, ViewHolder and data all work together.

Image for post

Creating an Adapter

Create a class called FlowerAdapter that takes two arguments in its constructor: a list of data to display and the context for the activity in which it is displayed.

Read More  Enforce Ingress Best Practices Using OPA
<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowerAdapter(val flowerList: Array<String>) {

}

Creating a ViewHolder

Create an inner class called FlowerViewHolder that takes in an itemView. In the ViewHolder, create a val to represent the TextView and connect it with the view in the cell layout.

Then create a bind() function which connects the data for the flower name (String) and the UI that holds that data (flowerTextView) that takes a string. The bind() function takes the string passed in and assigns it as the text of flowerTextView.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
  private val flowerTextView:TextView = itemView.findViewById(R.id.flower_text)
  fun bind(word: String){
    flowerTextView.text = word
  }
}

Extending RecyclerView.Adapter

Update the FlowerAdapter class signature to extend the RecyclerView.Adapter class and pass the FlowerViewHolder in.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowerAdapter(val flowerList: Array<String>) :
    RecyclerView.Adapter<FlowerAdapter.FlowerViewHolder>() {
   
}

Classes that override RecyclerView.Adapter need to override three methods: onCreateViewHolder(), onBindViewHolder(), and getItemCount().

Overriding onCreateViewHolder()

This method is called when the ViewHolder is created. It initializes and inflates the view for the item in the RecyclerView. This view uses the item layout created earlier which displays text.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

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

Overriding onBindViewHolder()

onBindViewHolder() is called with the ViewHolder and a “position,” which denotes the item’s position in the flowerList that is being bound. This position can be used to extract the underlying data for the cell and pass that into the ViewHolder to bind the data to that holder’s UI.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

override fun onBindViewHolder(holder: FlowerViewHolder, position: Int) {
  holder.bind(flowerList[position])
}

Overriding getItemCount()

The RecyclerView displays a list, so it needs to know how many items are in the list. Since flowerList is the dataset, return its size.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

override fun getItemCount(): Int {
  return flowerList.size
}

Complete Adapter code

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class FlowerAdapter(val flowerList: Array<String>) :
    RecyclerView.Adapter<FlowerAdapter.FlowerViewHolder>() {

    // Describes an item view and its place within the RecyclerView
    class FlowerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val flowerTextView: TextView = itemView.findViewById(R.id.flower_text)

        fun bind(word: String) {
            flowerTextView.text = word
        }
    }

    // Returns a new ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FlowerViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.flower_item, parent, false)

        return FlowerViewHolder(view)
    }

    // Returns size of data list
    override fun getItemCount(): Int {
        return flowerList.size
    }

    // Displays data at a certain position
    override fun onBindViewHolder(holder: FlowerViewHolder, position: Int) {
        holder.bind(flowerList[position])
    }
}

Connecting to the MainActivity

The layout, data list, and adapter are all created! Now, just add the RecyclerView to the MainActivity and assign the Adapter to it.

Define a val called recyclerView and set it equal to the RecyclerView container in activity_main. Assign FlowerAdapter as your recyclerView’s adapter.

<!-- Copyright 2019 Google LLC. 
   SPDX-License-Identifier: Apache-2.0 -->

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val flowerList = Datasource().loadFlowers()
    val recyclerView: RecyclerView = findViewById(R.id.recycler_view)
    recyclerView.adapter = FlowerAdapter(flowerList)
  }

Now run the app and see it in action:

Image for post

 

Next Steps

The full code is posted here.

This example shows how to implement the basic pieces of RecyclerView to display simple text items. Of course, RecyclerView can handle more interesting and complex items as well, which I will investigate in future articles and samples. Until then check out these resources:

  • RecyclerView Sample — Kotlin
  • RecyclerView Sample — Java
  • RecyclerView Documentation
  • Create a List with RecyclerView

Let me know in the comments what topics you would be interested in learning more about!

By Meghan Mehta


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

aster.cloud

Related Topics
  • Android
  • Medium
  • RecyclerView
  • UI Widget
You May Also Like
View Post
  • DevOps
  • Engineering
  • Platforms

How To Fail At Platform Engineering

  • March 11, 2024
View Post
  • Computing
  • DevOps
  • Platforms

The IBM Approach To Reliable Quantum Computing

  • November 28, 2023
DevOps artifact management
View Post
  • Design
  • DevOps
  • Engineering

10 Awesome Benefits Of Artifact Management And Why You Need It

  • August 2, 2023
Automation | Gears
View Post
  • Automation
  • DevOps
  • Engineering

Automating CI/CD With GitHub Actions

  • June 13, 2023
View Post
  • Architecture
  • Data
  • Engineering
  • People
  • Programming
  • Software Engineering
  • Technology
  • Work & Jobs

Predictions: Top 25 Careers Likely In High Demand In The Future

  • June 6, 2023
View Post
  • DevOps
  • People

What’s The Future Of DevOps? You Tell Us. Take The 2023 Accelerate State Of DevOps Survey

  • June 2, 2023
View Post
  • Programming
  • Software Engineering
  • Technology

Build a Python App to Alert You When Asteroids Are Close to Earth

  • May 22, 2023
View Post
  • Programming

Illuminating Interactions: Visual State In Jetpack Compose

  • May 20, 2023

Stay Connected!
LATEST
  • 1
    Just make it scale: An Aurora DSQL story
    • May 29, 2025
  • 2
    Reliance on US tech providers is making IT leaders skittish
    • May 28, 2025
  • Examine the 4 types of edge computing, with examples
    • May 28, 2025
  • AI and private cloud: 2 lessons from Dell Tech World 2025
    • May 28, 2025
  • 5
    TD Synnex named as UK distributor for Cohesity
    • May 28, 2025
  • Weigh these 6 enterprise advantages of storage as a service
    • May 28, 2025
  • 7
    Broadcom’s ‘harsh’ VMware contracts are costing customers up to 1,500% more
    • May 28, 2025
  • 8
    Pulsant targets partner diversity with new IaaS solution
    • May 23, 2025
  • 9
    Growing AI workloads are causing hybrid cloud headaches
    • May 23, 2025
  • Gemma 3n 10
    Announcing Gemma 3n preview: powerful, efficient, mobile-first AI
    • May 22, 2025
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    Cloud adoption isn’t all it’s cut out to be as enterprises report growing dissatisfaction
    • May 15, 2025
  • 2
    Hybrid cloud is complicated – Red Hat’s new AI assistant wants to solve that
    • May 20, 2025
  • 3
    Google is getting serious on cloud sovereignty
    • May 22, 2025
  • oracle-ibm 4
    Google Cloud and Philips Collaborate to Drive Consumer Marketing Innovation and Transform Digital Asset Management with AI
    • May 20, 2025
  • notta-ai-header 5
    Notta vs Fireflies: Which AI Transcription Tool Deserves Your Attention in 2025?
    • May 16, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.