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.
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.
- <?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:orientation="vertical">
-
- <android.support.v7.widget.RecyclerView
- android:id="@+id/recyclerView"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
- </LinearLayout>
Then create a list item for your ListView. Create a Layout file and add the following lines.
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:focusable="true"
- android:paddingLeft="16dp"
- android:paddingRight="16dp"
- android:paddingTop="10dp"
- android:paddingBottom="10dp"
- android:clickable="true"
- android:background="?android:attr/selectableItemBackground"
- android:orientation="vertical">
-
- <TextView
- android:id="@+id/title"
- android:textColor="@color/title"
- android:textSize="16sp"
- android:textStyle="bold"
- android:layout_alignParentTop="true"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
-
- <TextView
- android:id="@+id/genre"
- android:layout_below="@id/title"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
-
- <TextView
- android:id="@+id/year"
- android:textColor="@color/year"
- android:layout_width="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_height="wrap_content" />
- </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.
- class Movies {
- var title: String = ""
- var genre: String = ""
- var year: String = ""
-
- constructor() {}
-
- constructor(title: String, genre: String, year: String) {
- this.title = title
- this.genre = genre
- this.year = year
- }
- }
Now create an adapter for your RecyclerView, and in my case, I created “MoviesRecyclerAdapter.kt”. Then add the following code to your adapter class.
- class MoviesRecyclerAdapter(private val moviesList: List<Movies>) : RecyclerView.Adapter<MoviesRecyclerAdapter.MyViewHolder>() {
-
- inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
- var title: TextView = view.findViewById<TextView>(R.id.title)
- var year: TextView = view.findViewById<TextView>(R.id.year)
- var genre: TextView = view.findViewById<TextView>(R.id.genre)
-
- }
-
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
- val itemView = LayoutInflater.from(parent.context)
- .inflate(R.layout.movie_list_row, parent, false)
-
- return MyViewHolder(itemView)
- }
-
- override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
- val Movies = moviesList[position]
- holder.title.text = Movies.title
- holder.genre.text = Movies.genre
- holder.year.text = Movies.year
- }
-
- override fun getItemCount(): Int {
- return moviesList.size
- }
- }
- 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.
- recyclerView = findViewById(R.id.recyclerView) as RecyclerView
- mAdapter = MoviesRecyclerAdapter(movieList)
- val mLayoutManager = LinearLayoutManager(applicationContext)
- recyclerView!!.layoutManager = mLayoutManager
- recyclerView!!.itemAnimator = DefaultItemAnimator()
- 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.
- class RecyclerViewActivity : AppCompatActivity() {
- private var movieList = ArrayList<Movies>()
- private var recyclerView: RecyclerView? = null
- private var mAdapter: MoviesRecyclerAdapter? = null
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_recyclerview)
-
- recyclerView = findViewById(R.id.recyclerView) as RecyclerView
-
- mAdapter = MoviesRecyclerAdapter(movieList)
- val mLayoutManager = LinearLayoutManager(applicationContext)
- recyclerView!!.layoutManager = mLayoutManager
- recyclerView!!.itemAnimator = DefaultItemAnimator()
- recyclerView!!.adapter = mAdapter
-
- prepareMoviesData()
- }
-
- private fun prepareMoviesData() {
- var movie = Movies("Mad Max: Fury Road", "Action & Adventure", "2015")
- movieList.add(movie)
-
- movie = Movies("Inside Out", "Animation, Kids & Family", "2015")
- movieList.add(movie)
-
- movie = Movies("Star Wars: Episode VII - The Force Awakens", "Action", "2015")
- movieList.add(movie)
-
- movie = Movies("Shaun the Sheep", "Animation", "2015")
- movieList.add(movie)
-
- movie = Movies("The Martian", "Science Fiction & Fantasy", "2015")
- movieList.add(movie)
-
- movie = Movies("Mission: Impossible Rogue Nation", "Action", "2015")
- movieList.add(movie)
-
- movie = Movies("Up", "Animation", "2009")
- movieList.add(movie)
-
- movie = Movies("Star Trek", "Science Fiction", "2009")
- movieList.add(movie)
-
- movie = Movies("The LEGO Movies", "Animation", "2014")
- movieList.add(movie)
-
- movie = Movies("Iron Man", "Action & Adventure", "2008")
- movieList.add(movie)
-
- movie = Movies("Aliens", "Science Fiction", "1986")
- movieList.add(movie)
-
- movie = Movies("Chicken Run", "Animation", "2000")
- movieList.add(movie)
-
- movie = Movies("Back to the Future", "Science Fiction", "1985")
- movieList.add(movie)
-
- movie = Movies("Raiders of the Lost Ark", "Action & Adventure", "1981")
- movieList.add(movie)
-
- movie = Movies("Goldfinger", "Action & Adventure", "1965")
- movieList.add(movie)
-
- movie = Movies("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014")
- movieList.add(movie)
-
- mAdapter!!.notifyDataSetChanged()
- }
- }
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.