Android RecyclerView Tutorial Using Kotlin

Learning to use RecyclerView in Android development is very crucial for every programmers. It is one of powerful widgets to display a list of data in Android. Well in this chance I will give you a simple tutorial to help you understand how to use RecyclerView to display list of data from me using Kotlin.

What is RecyclerView?

Basically RecyclerView is more like a combination of ListView and GridView with more enhanced feature. What I mean about enhanced feature is because RecyclerView do the memory efficiency job better. It works by recycling the layout when user scroll the data. You’ll know about it more as you keep learning. I won’t talk about it here because the explanation would be long and confuse you, so you could learn it later.

What will we learn here?

Okay, we’re gonna create a simple application to display list of DC superheroes using Android RecyclerView. Who’s DC fans here? Basically it will display the picture, name, and origin of each heroes. So let’s create it shall we!

Note: In this post I used Android Studio 3.2.1 so the appearance might or might not be similar like yours and it’s okay though, but make sure you use the latest Android Studio, or if you already install it, be sure to check the latest update. The Kotlin version that I used is Kotlin 1.3.11.

Getting Started

Open your Android Studio and choose Start a new Android Studio Project.

Android RecyclerView Tutorial Using Kotlin

 

Give the Application Name DCHeroes and don’t forget to check the Include Kotlin Support checkbox. After that give the Activity Name MainActivity like always. Wait until the Android Studio finish preparing your project.

Open your build.gradle file under app directory like this image below:

Add the following code inside dependencies to import RecyclerView for our app.

implementation 'com.android.support:recyclerview-v7:28.0.0'

 

After that Android Studio will prompt you to sync the Gradle so click Sync Now and wait until it finishes.

 

Creating Layout

Now is the time to create our layout. Open activity_main.xml and write the entire code to this code below.

<?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="match_parent">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recyclerView"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>

</LinearLayout>

 

It is a very basic usage of RecyclerView inside the xml layout. So we’re creating a single RecyclerView inside LinearLayout that fill the entire screen.

Creating Data and Adapter

In order to use Android RecyclerView, we have to create a class that will manage our data set and it is called the Adapter. So basically Adapter will manage our data that will be displayed on each row of RecyclerView. Okay good, now we will create a data class called Hero. Right click on your root package (ie. com.yourdomain.dcheroes), choose New > Kotlin File/Class.

 

In New Kotlin File/Class dialog, type Hero inside Name and choose Class inside Kind selection box. After that click OK.

 

Type this code inside your newly Hero.kt file:

data class Hero(
   val pictureUrl: String,
   val name: String,
   val origin: String
)

 

Okay we finished creating the data class and next, create a new Layout resource file inside the res/layout directory.

 

On New Resource File dialog, give the File name to item_hero and Root element to LinearLayout. Click OK button.

 

The new layout file item_hero.xml will be created. Open it and write this code inside:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="wrap_content">

   <LinearLayout
       android:id="@+id/container"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:background="?selectableItemBackground"
       android:clickable="true"
       android:paddingLeft="20dp"
       android:paddingRight="20dp"
       android:paddingTop="12dp"
       android:paddingBottom="12dp"
       android:gravity="center_vertical">

       <ImageView
           android:id="@+id/ivHeroPicture"
           android:layout_width="50dp"
           android:layout_height="50dp" />

       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:orientation="vertical"
           android:layout_marginLeft="12dp">

           <TextView
               android:id="@+id/tvHeroName"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textStyle="bold"
               android:textSize="16sp"
               android:text="Hero Name"/>

           <TextView
               android:id="@+id/tvHeroOrigin"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="2dp"
               android:text="Origin"/>

       </LinearLayout>

   </LinearLayout>

   <View
       android:layout_width="match_parent"
       android:layout_height="1dp"
       android:background="#dedede"/>

</LinearLayout>

 

I will explain a bit from the layout code above. There is one ImageView to display the picture URL of our hero, and two TextView for displaying the name and origin of hero data. I will not use a complex layout here cause I don’t want to confuse you.

OK then add another new Kotlin file again. Give HeroesAdapter inside Name and choose Class inside Kind selection box. After that click OK.

 

Open HeroesAdapter.kt and write this code:

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_hero.view.*

class HeroesAdapter(private val itemList: List<Hero>): RecyclerView.Adapter<HeroesAdapter.ViewHolder>() {

   private var context: Context? = null

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

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

   override fun onBindViewHolder(holder: HeroesAdapter.ViewHolder, position: Int) {
       holder.bind()
   }

   inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

       fun bind() {
           val data = itemList.get(adapterPosition)
           itemView.tvHeroName.text = "${data.name}"
           itemView.tvHeroOrigin.text = "${data.origin}"
       }

   }
}

 

There are four core elements of RecyclerView Adapter:

  • ViewHolder class is a holder for our each of our data. You have to place the view from layout here and you can also set the data to the view from this place.
  • onCreateViewHolder() is a place where we define what layout that will be used for each data row. This method must returns a ViewHolder object. In our app, we will use item_hero.xml that we have created before.
  • getItemCount() will return the size or count of the dataset. If you have 20 items so you will have to write 20 as return. For our case here, it depends on the list of our heroes data so we write it return itemList.size
  • onBindViewHolder() is a place where the data and the ViewHolder is connected. This is where each of your view is binded to each of data.

Okay the next step is we have to connect the Adapter to our Android RecyclerView so open MainActivity.kt. Add this code inside it:

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

   private val heroList = ArrayList<Hero>()

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

       // init data
       initData()

       // init recyclerview
       recyclerView.layoutManager = LinearLayoutManager(this)
       recyclerView.adapter = HeroesAdapter(heroList)
   }

   private fun initData() {
       heroList.add(Hero("https://i.ibb.co/FDxPzDn/batman.jpg",
           "Batman", "Gotham City"))
       heroList.add(Hero("https://i.ibb.co/cJmt652/superman.jpg",
           "Superman", "Krypton"))
       heroList.add(Hero("https://i.ibb.co/gdxx4qV/Wonder-Woman.jpg",
           "Wonder Woman", "Themyscira"))
       heroList.add(Hero("https://i.ibb.co/xDgdJSG/theflash.jpg",
           "The Flash", "Central City"))
       heroList.add(Hero("https://i.ibb.co/J75K6kT/aquaman.jpg",
           "Aquaman", "Atlantis"))
       heroList.add(Hero("https://i.ibb.co/yfcMKP0/greenlantern.jpg",
           "Green Lantern", "Coast City"))
       heroList.add(Hero("https://i.ibb.co/f0YbwWy/cyborg.jpg",
           "Cyborg", "Central City"))
   }
}

 

In this MainActivity.kt file, I put an ArrayList that will hold our Hero data and I give it the name of heroList. Inside the onCreate() method, I place the initData() method which is doing the  addition of heroes data. After that, we connect and the RecyclerView with our HeroesAdapter. I also put the heroList data items inside the HeroesAdapter.

Open the AndroidManifest.xml and add this permission code just above the <application> tag:

<uses-permission android:name="android.permission.INTERNET" />

 

Wow, it’s a lot of codes until this! Yeah don’t worry, you will get used to this kind of things when using Android RecyclerView as you have more practices. Finally, you can run the app now.

Android RecyclerView Tutorial Using Kotlin

 

Hmm, something’s missing here, the picture is not displayed. Well that’s because we haven’t load it yet. So in order to load the picture from URL to our ImageView, we have to display it differently. We will use a powerful tool or library to load our images, the Glide library. So what is that? Loading image In Android RecyclerView is very hard because we have to handle the disk caching, decoding, memory, etc. So Glide will do the hard works for us, no need to reinvent the wheel, ain’t it? For more information about Glide you can go here.

Setting up Glide

Open the build.gradle file inside the root project directory of the app.

 

Find the allprojects and add the mavenCentral() like this:

allprojects {
   repositories {
       google()
       jcenter()
       mavenCentral()
   }
}

 

Also open the build.gradle inside the app directory and add the implementation of Glide like this inside dependencies.

implementation 'com.github.bumptech.glide:glide:4.8.0'
kapt 'com.github.bumptech.glide:compiler:4.8.0'

 

After that sync the Gradle file. Add a new Kotlin file called MyAppGlideModule.kt and write this code inside it:

import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule

@GlideModule
class MyAppGlideModule : AppGlideModule()

 

After you write it, open again the HeroesAdapter.kt file and find the bind() method inside ViewHolder class and add the Glide code like this:

fun bind() {
   val data = itemList.get(adapterPosition)
   itemView.tvHeroName.text = "${data.name}"
   itemView.tvHeroOrigin.text = "${data.origin}"

   // load image
   GlideApp.with(context!!)
       .load(data.pictureUrl)
       .circleCrop()
       .diskCacheStrategy(DiskCacheStrategy.ALL)
       .into(itemView.ivHeroPicture)
}

 

Don’t forget to also add this to imports:

import com.bumptech.glide.load.engine.DiskCacheStrategy

 

Now your app here is done, you can now run again. You will see the images now is displayed. Congratulation!

Android RecyclerView Tutorial Using Kotlin

 

Where to go next?

You can download this entire code from my github repo here. In the next post I will show you how to create a simple image gallery Android application using Kotlin, so stay tuned. Be sure to check my other post here about a simple Mystery Box app to learn about using TextView, ImageView, and Button for Android. Hope you like my post, comment and share it with love!

You may also like...

1 Response

  1. February 23, 2020

    […] It is just a typical Adapter code for Android RecyclerView. If you want to learn more about working with Android RecyclerView, you can go here. […]

Join the discussion...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: