Home / Programming / Android / All you need to know about RecyclerView + Example

All you need to know about RecyclerView + Example

Welcome to RecyclerView!

What is a RecyclerView?

RecyclerView is a container for displaying large data sets that can be scrolled (vertical or horizontal) very efficiently by maintaining a limited number of views.

An Adapter is necessary to pull content from a source such as an array or database. An adapter actually bridges between UI components and the data source that fill data into UI Component.

Every piece of recycler view is completely modular to allow for easy customisations such as animations, layout style (linear, grid or staggered layout), listeners and so on.

When to use a RecyclerView

It’s ideal to use to use a RecyclerView when the data to be presented is similar and has unpredictable quantity but also large (depending on the user).

Ideal use cases are Photo Gallery App, Gmail, ToDo List App, Chat Apps etc.

It is impractical and memory consuming to create views for each data because User A might have 10 photos in her Gallery while User B might have 10 thousand. Now, let’s imagine creating 10,000 imageView’s to display User B’s content. Our app would consistently crash due to lack of memory to display all 10 thousand pictures at once. RecyclerView solves this problem by caching and re-using views.

How does RecyclerView work?

Good Question.

When a RecyclerView is successfully initialised with an adapter, the adapter creates a number of views that fills the visible screen plus extra views above and below the screen. For instance, If your screen can accommodate 7 row items, the adapter would create 7+ ViewHolders. This is done in order to handle fast flings and smoothly scroll through a list from an array or data source. ViewHolders are created in onCreateViewHolder. By employing the ViewHolder pattern, RecyclerView adapter can recycle or create new ViewHolders when needed, which is far more efficient than creating new views for each item.

  1. Adapter : The recycler view adapter is used to provide the recycler view with new views when needed and can also be used to bind data from some data source to the views. The adapter sends views to an object called a ViewHolder. In order to create RecyclerView adapter you need to sub-cass RecyclerView.Adapter while passing in a generic subclass of RecyclerView.ViewHolder.
  2. ViewHolder: describes an item view and metadata about its place within the RecyclerView. When recycler view is first being populated you call findViewById for each view that will be showing data from the adaptor, this search can be expensive especially if you have a hierarchy of view in your list item. So it’s best to do it once and cache it in a viewHolder. This way you can access the views later without having to look them up repeatedly

Let’s talk about the Recycler.Adapter class :

  • it mandates the implementation of View Holder pattern (which is fancy word for re-using views to inflate data instead of creating views for every data in the array or data source)
  • it mandates overriding 3 methods – onCreateViewHolder, getItemCount, onBindViewHolder.
  • onCreateViewHolder is called when you need a new View. If there is an available Recycled View that can be provided and be bound with new data, then onBindViewHolder is called.
  • onBindViewHolder is used to update the RecyclerView.ViewHolder contents with the item at the given position and also sets up some private fields to be used by RecyclerView.
  • getItemCount returns the total number of items in the data set held by the adapter.

How to use Recycler View

To use the recycler view, you will need a view holder and an adapter. Adapters are used to link UI elements with code, while view holders contain views.

Basic Tutorial on Recycler View

Source Code is Available on GitHub

1. Add Recycler View dependency to your build.grade(Module : App) file

As of this writing, the latest version is implementation ‘com.android.support:recyclerview-v7:27.1.1

Check for latest support library versions

2. Activity Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.v7.widget.RecyclerView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/recycler_view"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

3. Layout that displays data in Rows – recycler_view_row.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content">

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:textColor="#000000"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Title 1" />

<TextView
android:id="@+id/sub_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/title"
tools:text="This is Sub-TITLE 1 with a summary" />

</android.support.constraint.ConstraintLayout>

4. MainActivity.kt

class MainActivity : AppCompatActivity() {

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

        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        val recyclerViewItemDivider = DividerItemDecoration(this, LinearLayoutManager.VERTICAL)
        recyclerView.addItemDecoration(recyclerViewItemDivider)
        val recyclerViewAdapter = RecyclerViewAdapter(generateDummyData())
        recyclerView.adapter = recyclerViewAdapter
    }

    private fun generateDummyData(): List<DummyData> {
        val dummyDataList = ArrayList<DummyData>()
        for (x in 0..50) {
            dummyDataList.add(DummyData("Title $x", "This is Sub-TITLE $x with a summary"))
        }
        return dummyDataList
    }

    class RecyclerViewAdapter(var dummyDataList: List<DummyData>) : RecyclerView.Adapter<ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_view_row, parent, false)
            return ViewHolder(view)
        }

        override fun getItemCount() = dummyDataList.size

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.titleTextView.setText(dummyDataList[position].title)
            holder.subTitleTextView.setText(dummyDataList[position].subtitle)
        }
    }
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val titleTextView: TextView
        val subTitleTextView: TextView

        init {
            titleTextView = view.findViewById(R.id.title)
            subTitleTextView = view.findViewById(R.id.sub_title)
            view.setOnClickListener { view ->
                Toast.makeText(view.context,"You clicked on Item ${adapterPosition}", Toast.LENGTH_SHORT).show()

            }
        }
    }
}
Summary
Article Name
All you need to know about RecyclerView + Example
Description
RecyclerView is a container for displaying large data sets that can be scrolled (vertical or horizontal) very efficiently by maintaining a limited number of views. Grab sample code on GitHub
Author
Publisher Name
Edge Dev Studio
Publisher Logo

About Edge Developer

Hey there! am Opeyemi Olorunleke (aka Edge Developer), an Android developer. I Love Sharing Android Tutorials and code snippets.

Check Also

Android Admob Consent SDK : All you need to know + Example

First of all, let me address Google’s complacency to help app developers implement the GDPR …

Leave a Reply

Your email address will not be published. Required fields are marked *