Create RecyclerView in Kotlin Programmatically

Below is a very short tutorial on how to create RecyclerView in Kotlin programmatically. RecyclerView is a flexible view for providing a limited window into a large data set and learning how to create and use it make you even better Mobile App Developer :).

The Kotlin code example below will cover:

  • Create RecyclerView
  • Create RecyclerAdapter
  • Create a Model for populating RecyclerView with items
  • Create ViewHolder
  • Use of LinearLayoutManager

And the end result will look like this:

Create RecyclerView Programmatically in Kotlin
Create RecyclerView Programmatically in Kotlin

Let’s first create two XML file which are needed to create a layout for our RecyclerView:

  1. activity_recycler_view_example.xml to hold the RecyclerView.
  2. recycler_list_layout.xml which will define layout for the items inside of the our list. We will use this layout file inside of the MyAdapter class example of which you will see below.

XML Layout for RecyclerView

The first xml file will be to hold the RecyclerView itself. Create a new xml layout file and call it something like activity_recycler_view_example.xml. Paste in the below xml content but make sure you change the package name in it. The package name I have in the below xml file belongs to my project. Yours will be different.

The following is the activity_recycler_view_example.xml contains an empty LinearLayout to which we will add the RecyclerView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/linearLayout"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.appsdeveloperblog.kotlin.examples.RecyclerViewExample"
    android:orientation="horizontal">

</LinearLayout>

XML Layout for RecyclerView List

Create a new xml file and paste the following content in it. You can keep it as is. This file does not have project’s package name in it. In my case this file is called: recycler_list_layout.xml

<?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:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:paddingLeft="16dp"
            android:paddingBottom="4dp"
            android:text="TextView"
            android:textSize="24dp" />

        <View
            android:layout_width="match_parent"
            android:layout_height=".5dp"
            android:background="@color/cardview_dark_background" />
    </android.support.v7.widget.CardView>

</LinearLayout>

Data class

Create a data class SeriesModel.kt to classify and contain a single data.

package com.appsdeveloperblog.kotlin.examples
 
data class SeriesModel (val name: String)

The Adapter and ViewHolder classes

Create MyAdapter.kt file with the code below. This Kotlin file contains two classes, MyAdapter class which takes an ArrayList of SeriesModel and send it recycler_list_layout.xml to show. And The MyViewHolder will assign the values from the model to their corresponding views.

package com.appsdeveloperblog.kotlin.examples

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
 
class MyAdapter(private val seriesList: ArrayList<SeriesModel>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

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


    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.textViewName.text = seriesList[position].name
    }


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


    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val textViewName = itemView.findViewById(R.id.name) as TextView

    }
}

RecyclerView AppCompatActivity Class

And finally here is the main Kotlin class which creates the RecyclerView. In this class we create an Arraylist of SeriesModel containing the titles of the elements which are displayed in the list and then we pass this array of elements to MyAdapter class(the source code of which is right above), to display the content of our ArrayList.

package com.appsdeveloperblog.kotlin.examples

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.LinearLayout


class RecyclerViewExample : AppCompatActivity() {

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

        val linearLayout = findViewById(R.id.linearLayout) as LinearLayout
        val recyclerView =  RecyclerView(this)

        val series = ArrayList<SeriesModel>()
        series.add(SeriesModel("Rick and Morty"))
        series.add(SeriesModel( "IT Crowd"))
        series.add(SeriesModel("Game of Thrones"))
        series.add(SeriesModel("Silicon Valley"))
        series.add(SeriesModel("Person of Interest"))
        series.add(SeriesModel("Friends"))
        series.add(SeriesModel("The Big Bang Theory"))
        series.add(SeriesModel("The Band of Brothers"))
        series.add(SeriesModel("Breaking Bad"))
        series.add(SeriesModel("Rome"))
        series.add(SeriesModel("How I Met Your Mother"))
        series.add(SeriesModel("House of Cards"))
        series.add(SeriesModel("Sherlock"))
        series.add(SeriesModel("Prison Break"))
        series.add(SeriesModel("The Vinci's Demon"))
        series.add(SeriesModel("The Simposons"))
        series.add(SeriesModel("Attack on titans"))
        series.add(SeriesModel("MR. Robot"))
        series.add(SeriesModel("Cosmos"))
        series.add(SeriesModel("Westworld"))

        val adapter = MyAdapter(series)
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(this,LinearLayout.VERTICAL, false)
        recyclerView.adapter = adapter

        linearLayout.addView(recyclerView)
    }

}

And this is it. Build and run this example and if everything went well you should get back a list of items which is as on the picture in this blog post.

Check out other Kotlin code examples and tutorials in the Kotlin category.  Many of them are simply copy and paste to use. To learn more about building mobile apps for Android with Kotlin, check out the below list of books and video courses.

Happy learning!

 

Building Mobile Apps with Kotlin for Android

 

Building Mobile Apps with Kotlin and Firebase

Kotlin. Video Courses.

The Complete Android Kotlin Developer Course

Learn how to make online games, and apps for Android O, like Pokémon , twitter,Tic Tac Toe, and notepad using Kotlin. The Complete Android Kotlin Developer Course icon

Kotlin for Java Developers

Use your Java skills to learn Kotlin fast. Enhance career prospects and master Kotlin, including Java interoperability. Kotlin for Java Developers icon

Kotlin for Beginners: Learn Programming With Kotlin

Learn Kotlin from scratch! Grasp object-orientation and idiomatic Kotlin to realize coding projects and Android apps! Kotlin for Java Developers icon