How to create a basic recyclerview in Android using Kotlin

How to create a basic recyclerview in Android using Kotlin:

In this post, we will learn how to create one simple recyclerview in Android using Kotlin. In Android, to show a scrollable list of items, we can either use one ListView or one RecyclerView. RecyclerView is an advanced version of ListView.

RecyclerView is bit hard to understand. So, instead of showing you a complex recyclerview, I will show you one simple recyclerview in this blog post. If you understand the basics, you can create any type of recyclerview with different functionalities.

What we will build:

We will create one simple list of texts. We will load the list from an array of strings.

RecyclerView basic components:

Following are the main components that we need to create a RecyclerView :

  1. RecyclerView view. This is the main view that we need to include in our xml file.
  2. Layout file for each row.
  3. For each RecyclerView, we need to assign the following two components:
    1. A layout manager. Android provides us two layout managers: LinearLayoutManager and GridLayoutManager. We can also create our own layout managers.
    2. An adapter. Adapter is responsible to create new items, load data in the items and manage the items when the recyclerview scrolls. We need to create one adapter class extending RecyclerView.Adapter.
      1. ViewHolder. Adapter uses ViewHolder to load the layout file for each row and populates data to it.

Android project:

For this example, create one basic android studio project with one activity MainActivity.kt and its layout file activity_main.xml. For using RecyclerView, we need to add it as a dependency in our project. Open your App level build.gradle file and add the below dependency inside dependencies{} tab:

implementation "androidx.recyclerview:recyclerview:1.1.0"

Change the version number to latest if Android Studio is showing a warning message. Sync your project before moving to the next steps.

1. Create the RecyclerView View:

You can search for RecyclerView in the Design panel and drag drop it in your view or you can edit the xml file and add it.

recyclerview view

Or,

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycler_view"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

2. Create layout xml for recyclerview item:

Create one new xml file list_item.xml and add the below code:

<?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:gravity="center">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp" />
</LinearLayout>

Here, we have only one TextView for each recyclerview item because we are showing only one text for each item.

3. Change the activity:

package com.codevscolor.myapplication

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    val  values = arrayOf("one", "two" , "three", "four", "five" , "six", "seven", "eight", "nine", "ten")

    private lateinit var recyclerView: RecyclerView
    private lateinit var manager: RecyclerView.LayoutManager
    private lateinit var myAdapter: RecyclerView.Adapter<*>

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

        manager = LinearLayoutManager(this)
        myAdapter = MyAdapter(values)

        recyclerView = findViewById<RecyclerView>(R.id.recycler_view).apply {
            layoutManager = manager
            adapter =  myAdapter
        }

    }
}

class MyAdapter(private val myDataSet : Array<String>):
    RecyclerView.Adapter<MyAdapter.ViewHolder>() {

    class ViewHolder(val view: View): RecyclerView.ViewHolder(view){
        fun bind(text: String){
            val tv = view.findViewById<TextView>(R.id.textView)
            tv.text = text
        }
    }

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

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

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

}

Here,

  • manager is a LinearLayoutManager that we are assigning to the RecyclerView.
  • MyAdapter is the recyclerview adapter
  • ViewHolder is the view holder for the recyclerview items.
  • values is an array of strings that we are loading to the recyclerview. This array is passed to the adapter and adapter decides which value to pick from this item for which element in the list.

Inside the adapter class, we are overriding three methods:

  • getItemCount method is called to get the total number of elements to show in the recyclerview. We are returning the string array length.
  • onCreateViewHolder is called when a view holder is created. It returns one object of view holder i.e. our view holder class object ViewHolder. We are passing the view of the list item i.e. list_item.
  • onBindViewHolder is called to bind the data to the view. We are calling the bind method of the view holder to load the data to the list element.

That’s it. If you run this program, it will load the data in a list as like below:

Android recyclerview

If you add more items to the array, it will load all of them in a list.

Android recyclerview