RecyclerView In Android - Kotlin

Kotlin

In this article, we will learn how to work with RecyclerView in Android using Kotlin. This article is the continuation of my previous article, “ListView in Android - Kotlin”.

 

Implementation of RecyclerView with custom adapter is similar to ListView implementation in Android using Kotlin.

Steps

I have split this article into 3 steps asfollows:

Step 1 - Creating a new Android Project with Kotlin in Android Studio.

Step 2 - Adding user interface in your layout file.

Step 3 - Implementing the ListView in Android applications.

Step 1 - Creating a new Android Project with Kotlin in Android Studio

By default, Android Studio 3.0 has a checkbox for Kotlin Support for your Android Application. Create a new project in Android studio, check the Kotlin support, and start as usual with Android Studio 3.0. 

Kotlin

For migrating Java Android Project to Kotlin Android Project, you can do the following:

Configuring Kotlin

Kotlin support can be configured by selecting Tools - Kotlin - Configure Kotlin. Then, Click “Sync Now”. This step is applicable to the Android Studio pre-versions of 3.0. The best way is you must update your Android Studio.

In Android Studio 3.0, by default, you have Kotlin Activity. For Android Studio with versions lower than 3.0, you can convert your Java activity into Kotlin Activity.

Open Quick Search or Click Ctrl + Shift + A for Windows Users, and select “Convert Java to Kotlin” or simply Select Ctrl + Shift + Alt + K. 

Step 2 - Adding User Interface in your Layout file

In this step, we will add RecyclerView in our Layout file. Open your activity_recyclerview.xml file and paste the following.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical">  
  6.   
  7.     <android.support.v7.widget.RecyclerView  
  8.         android:id="@+id/recyclerView"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" />  
  11. </LinearLayout>  

Then create a list item for your ListView. Create a Layout file and add the following lines.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:focusable="true"  
  6.     android:paddingLeft="16dp"  
  7.     android:paddingRight="16dp"  
  8.     android:paddingTop="10dp"  
  9.     android:paddingBottom="10dp"  
  10.     android:clickable="true"  
  11.     android:background="?android:attr/selectableItemBackground"  
  12.     android:orientation="vertical">  
  13.   
  14.     <TextView  
  15.         android:id="@+id/title"  
  16.         android:textColor="@color/title"  
  17.         android:textSize="16sp"  
  18.         android:textStyle="bold"  
  19.         android:layout_alignParentTop="true"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="wrap_content" />  
  22.   
  23.     <TextView  
  24.         android:id="@+id/genre"  
  25.         android:layout_below="@id/title"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="wrap_content" />  
  28.   
  29.     <TextView  
  30.         android:id="@+id/year"  
  31.         android:textColor="@color/year"  
  32.         android:layout_width="wrap_content"  
  33.         android:layout_alignParentRight="true"  
  34.         android:layout_height="wrap_content" />  
  35. </RelativeLayout>  

In the next step, we will learn how to initialize the ListView and its adapter.

Step 3 - Implementing the RecyclerView in Kotlin

Create a Model class for your ListView. Create Movies.kt class file and add the following lines.

  1. class Movies {  
  2.     var title: String = ""  
  3.     var genre: String = ""  
  4.     var year: String = ""  
  5.   
  6.     constructor() {}  
  7.   
  8.     constructor(title: String, genre: String, year: String) {  
  9.         this.title = title  
  10.         this.genre = genre  
  11.         this.year = year  
  12.     }  
  13. }  

Now create an adapter for your RecyclerView, and in my case, I created “MoviesRecyclerAdapter.kt”. Then add the following code to your adapter class.

  1. class MoviesRecyclerAdapter(private val moviesList: List<Movies>) : RecyclerView.Adapter<MoviesRecyclerAdapter.MyViewHolder>() {  
  2.   
  3.     inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {  
  4.         var title: TextView = view.findViewById<TextView>(R.id.title)  
  5.         var year: TextView = view.findViewById<TextView>(R.id.year)  
  6.         var genre: TextView = view.findViewById<TextView>(R.id.genre)  
  7.   
  8.     }  
  9.   
  10.     override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {  
  11.         val itemView = LayoutInflater.from(parent.context)  
  12.                 .inflate(R.layout.movie_list_row, parent, false)  
  13.   
  14.         return MyViewHolder(itemView)  
  15.     }  
  16.   
  17.     override fun onBindViewHolder(holder: MyViewHolder, position: Int) {  
  18.         val Movies = moviesList[position]  
  19.         holder.title.text = Movies.title  
  20.         holder.genre.text = Movies.genre  
  21.         holder.year.text = Movies.year  
  22.     }  
  23.   
  24.     override fun getItemCount(): Int {  
  25.         return moviesList.size  
  26.     }  
  27. }  
  • Here, I created a custom adapter with Holder. The Holder contains the members of the layout to bind further, for example “TextView”, “ImageView”, etc.

  • onCreateViewHolder
    The Row is inflated here.

  • onBindViewHolder
    The data from the activity/fragment is bound to the members of the holder.

Then create/open your activity and in my case I am opening “RecylerViewActivity.kt” and adding the following code.

  1. recyclerView = findViewById(R.id.recyclerView) as RecyclerView  
  2. mAdapter = MoviesRecyclerAdapter(movieList)  
  3. val mLayoutManager = LinearLayoutManager(applicationContext)  
  4. recyclerView!!.layoutManager = mLayoutManager  
  5. recyclerView!!.itemAnimator = DefaultItemAnimator()  
  6. recyclerView!!.adapter = mAdapter  

The Kotlin is a good language that will handle the null exception with nullable values. Here, recycleView has Nullable Values.

Full Code

You can find the full code implementation below.

  1. class RecyclerViewActivity : AppCompatActivity() {  
  2.     private var movieList = ArrayList<Movies>()  
  3.     private var recyclerView: RecyclerView? = null  
  4.     private var mAdapter: MoviesRecyclerAdapter? = null  
  5.   
  6.     override fun onCreate(savedInstanceState: Bundle?) {  
  7.         super.onCreate(savedInstanceState)  
  8.         setContentView(R.layout.activity_recyclerview)  
  9.   
  10.         recyclerView = findViewById(R.id.recyclerView) as RecyclerView  
  11.   
  12.         mAdapter = MoviesRecyclerAdapter(movieList)  
  13.         val mLayoutManager = LinearLayoutManager(applicationContext)  
  14.         recyclerView!!.layoutManager = mLayoutManager  
  15.         recyclerView!!.itemAnimator = DefaultItemAnimator()  
  16.         recyclerView!!.adapter = mAdapter  
  17.   
  18.         prepareMoviesData()  
  19.     }  
  20.   
  21.     private fun prepareMoviesData() {  
  22.         var movie = Movies("Mad Max: Fury Road""Action & Adventure""2015")  
  23.         movieList.add(movie)  
  24.   
  25.         movie = Movies("Inside Out""Animation, Kids & Family""2015")  
  26.         movieList.add(movie)  
  27.   
  28.         movie = Movies("Star Wars: Episode VII - The Force Awakens""Action""2015")  
  29.         movieList.add(movie)  
  30.   
  31.         movie = Movies("Shaun the Sheep""Animation""2015")  
  32.         movieList.add(movie)  
  33.   
  34.         movie = Movies("The Martian""Science Fiction & Fantasy""2015")  
  35.         movieList.add(movie)  
  36.   
  37.         movie = Movies("Mission: Impossible Rogue Nation""Action""2015")  
  38.         movieList.add(movie)  
  39.   
  40.         movie = Movies("Up""Animation""2009")  
  41.         movieList.add(movie)  
  42.   
  43.         movie = Movies("Star Trek""Science Fiction""2009")  
  44.         movieList.add(movie)  
  45.   
  46.         movie = Movies("The LEGO Movies""Animation""2014")  
  47.         movieList.add(movie)  
  48.   
  49.         movie = Movies("Iron Man""Action & Adventure""2008")  
  50.         movieList.add(movie)  
  51.   
  52.         movie = Movies("Aliens""Science Fiction""1986")  
  53.         movieList.add(movie)  
  54.   
  55.         movie = Movies("Chicken Run""Animation""2000")  
  56.         movieList.add(movie)  
  57.   
  58.         movie = Movies("Back to the Future""Science Fiction""1985")  
  59.         movieList.add(movie)  
  60.   
  61.         movie = Movies("Raiders of the Lost Ark""Action & Adventure""1981")  
  62.         movieList.add(movie)  
  63.   
  64.         movie = Movies("Goldfinger""Action & Adventure""1965")  
  65.         movieList.add(movie)  
  66.   
  67.         movie = Movies("Guardians of the Galaxy""Science Fiction & Fantasy""2014")  
  68.         movieList.add(movie)  
  69.   
  70.         mAdapter!!.notifyDataSetChanged()  
  71.     }  
  72. }  

Download Code

You can download the example code from GitHub for ListView and RecyclerView. If this article was useful to you, do like and star the repo on GitHub. Keep on commenting, if you have any doubts.


Similar Articles