How To Add RecyclerView Using Kotlin?

Want create site? Find Free WordPress Themes and plugins.

Since Kotlin is a new language, you will find it fairly difficult to come across examples as opposed to Java which was the preferable language used by Java Developers. In this blog, we will cover one example called ‘RecyclerView’, which helps make large sets of data more concise by listing them.

Now, assuming you are using the preview version for Android Studio (Canary) which has Kotlin support, we can move further.

Step I: Create a project in Android Studio:

Select File -> New -> New Project ->  Give an Application Name -> Tick “Include Kotlin support” & click Next -> Next -> Select an Empty Activity  & click Next -> Finish

Create a New Project

Create a New Project

 

Target Android Devices

Target Android Devices

 

Add an Activity to Mobile

Add Activity to Mobile

 

Configure Activity

Configure Activity

 

Step II: Adding Dependencies to your project.

Now, to get the dependencies covered. You have to fire the following lines of code for the two important files, i.e., build.gradle of your app and build.gradle of your project.

i) In your build.gradle of your app add the following:

 

dependencies {
   ...
   //for kotlin
   compile "org.jetbrains.anko:anko-common:$anko_version"
 
   //for recyclerview and cardview
   compile 'com.android.support:design:25.1.0'
   compile 'com.android.support:cardview-v7:25.1.0'
}


ii) Now in your build.gradle of your project add the following:

 

buildscript {
   ext.anko_version = '0.8.2'
 
   dependencies {
      ...
      classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
   }
}

 

Step III: Place the following code in your activity_main.xml file.

Here, we create a RecyclerView and give it an id.

activity_main.xml:

<android.support.design.widget.CoordinatorLayout

  xmlns:android=“http://schemas.android.com/apk/res/android”

  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:id=“@+id/rvAndroidVersions”

      android:layout_width=“match_parent”

      android:layout_height=“match_parent”

      />

 

</android.support.design.widget.CoordinatorLayout>

 

 

Step IV: Specify how the items look.

We now have to create a new layout, to make sure each item in the list looks like we expected it to. Additionally, we have to inflate it, in our adapters onCreateViewHolder(). Here, we will create a layout (item_android_version), by placing the below code.

item_android_version.xml :

<?xml version=“1.0” encoding=“utf-8”?>

<android.support.v7.widget.CardView xmlns:android=“http://schemas.android.com/apk/res/android”

  xmlns:tools=“http://schemas.android.com/tools”

  android:layout_width=“match_parent”

  android:layout_height=“wrap_content”>

 

  <RelativeLayout

      android:layout_width=“match_parent”

      android:layout_height=“wrap_content”>

 

      <ImageView

          android:id=“@+id/ivIcon”

          android:layout_width=“72dp”

          android:layout_height=“72dp”

          tools:src=“@mipmap/ic_launcher” />

 

      <TextView

          android:id=“@+id/tvName”

          android:layout_width=“match_parent”

          android:layout_height=“wrap_content”

          android:layout_toRightOf=“@+id/ivIcon”

          android:padding=“4dp”

          android:textAppearance=“@style/Base.TextAppearance.AppCompat.Large”

          tools:text=“Name” />

 

      <TextView

          android:id=“@+id/tvVersion”

          android:layout_width=“match_parent”

          android:layout_height=“wrap_content”

          android:layout_below=“@+id/tvName”

          android:layout_toRightOf=“@+id/ivIcon”

          android:padding=“4dp”

          android:textAppearance=“@style/Base.TextAppearance.AppCompat.Medium”

          tools:text=“Version x.x.x” />

  </RelativeLayout>

</android.support.v7.widget.CardView>

 

This is how your layout will look.

Item Android Version

 

Step V: Create a Data Class.

We will first create our data class, which is equivalent to a POJO class in Java.

Right Click on your package -> New -> Kotlin File/Class-> name of the class (e.g. MyAndroidOS)

Please note: Data is a keyword used in Kotlin to differentiate between a normal class and a POJO class. Then inside the constructor we give variable names. If you observe closely you will come to know that variable names are placed before their respective data types.

MyAndroidOS.kt :

package com.example.admin.recyclerviewkotlin
 
data class MyAndroidOS(var imageIcon : Int, var name: String, var version: String)

Step VI: Create an Adapter.

Now we have to create a new Kotlin file to create our Custom Adapter. I’ve named it MyAndroidAdapter.

MyAndroidAdapter.kt :

package com.example.admin.recyclerviewkotlin
 
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item_android_version.view.*
 
/*Here in constructor of MyAndroidAdapter we pass the ArrayList and a listener as we want to call them in our Main Activity*/
 
class MyAndroidAdapter(val myAndroidOSList: ArrayList, val listener: (MyAndroidOS) -&gt; Unit) : RecyclerView.Adapter() {
 
   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAndroidAdapter.ViewHolder {
       val v = LayoutInflater.from(parent.context).inflate(R.layout.item_android_version, parent, false)
       return ViewHolder(v)
   }
 
   override fun onBindViewHolder(holder: MyAndroidAdapter.ViewHolder, position: Int) {
       holder.bindItems(myAndroidOSList[position], listener)
   }
 
   override fun getItemCount(): Int {
       return myAndroidOSList.size
   }
 
   class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
 
       fun bindItems(myAndroidOS: MyAndroidOS, listener: (MyAndroidOS) -&gt; Unit) = with(itemView)  {
/*
 tvName, tvVersion, ivIcon are the ids which we have specified in item_android_version.xml and they are available to us due to kotlin extensions which we have added in our gradle and we also have imported in this class( import kotlinx.android.synthetic.main.item_android_version.view.* )
In this import you can write the name of any xml file without the need to bind it in your class file and thus get rid of findViewById
*/
           itemView.tvName.text = myAndroidOS.name  /*Like here we directly use tvName without using findViewById */
           itemView.tvVersion.text = myAndroidOS.version
           itemView.ivIcon.setImageResource(myAndroidOS.imageIcon)
           itemView.setOnClickListener{listener(myAndroidOS)}
           }
       }

Step VII: Now, we come to MainActivity.kt class:

package com.example.admin.recyclerviewkotlin
 
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
import org.jetbrains.anko.toast
 
 
class MainActivity : AppCompatActivity() {
 
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)
 
       //Bind the recyclerview
       val recyclerView = findViewById(R.id.rvAndroidVersions) as RecyclerView
 
       //Add a LayoutManager
       recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
       recyclerView.addItemDecoration(LinearLayoutSpaceItemDecoration(16))
 
       //Here we create an arraylist to store alMyAndroidOS using the data class MyAndroidOS
       val alMyAndroidOS = ArrayList()
 
       //Adding some data to the arraylist
       alMyAndroidOS.add(MyAndroidOS(R.drawable.cupcake,"Cupcake", "v1.5"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.donut1,"Donut", "v1.6"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.eclair,"Eclair", "v2.1"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.froyo,"Froyo", "v2.2.x"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.gingerbread,"Gingerbread", "v2.3.x"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.honeycomb,"Honeycomb", "v3.x"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.icecreamsandwich,"Ice Cream Sandwich", "v4.0.x"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.jellybean,"Jelly Bean", "v4.1.x"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.kitkat,"KitKat", "v4.4.x"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.lollipop,"Lollipop", "v5.0"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.marshmallow1,"Marshmallow", "v6.0"))
       alMyAndroidOS.add(MyAndroidOS(R.drawable.nougat,"Nougat", "v7.0"))
 
       // adding the adapter to recyclerView
       recyclerView.adapter = MyAndroidAdapter(alMyAndroidOS){
//Anko library has its own definition of toast which we have addded in build.gradle
               toast("${it.name} Clicked")//A toast that displays the name of OS which you clicked on
           }
 
       }
   }

Please note: Here in MainActivity, I’ve used LinearLayoutSpaceItemDecoration class to add item decoration to recycler view.

LinearLayoutSpaceItemDecoration.kt :

package com.example.admin.recyclerviewkotlin
 
import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View
 
class LinearLayoutSpaceItemDecoration(var spacing: Int) : RecyclerView.ItemDecoration() {
   override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
       if (outRect != null &amp;&amp; parent != null) {
           var position = parent.getChildAdapterPosition(view)
           outRect.left = spacing
           outRect.right = spacing
           outRect.bottom = spacing
           if (position &lt; 1) outRect.top = spacing
       }
   }
}

This is how your application looks.

Recycler view Kotlin

And when you click on an item, a toast is displayed.

Kotlin RecyclerView Examples

Please note: You can download the source code here.

Did you find apk for android? You can find new Free Android Games and apps.

Tags

Related Posts

Leave A Comment