In my previous post, I spoke briefly about the magical Kotlin-Android-Extension plugin. So if you are reading my post for the first first, then do take a moment to include the kotlin-Android-Extension plugin in your build.gradle as I will not be declaring any UI elements in the Kotlin File. Also, if you are new to Kotlin, please follow this article from the official kotlin website to include the dependencies needed to get started with Kotlin.
Alright then, Without further ado, let’s build a list using RecyclerView in Kotlin.
Starting with the dependencies, Here is my build.gradle file. Observe that I am adding the dependency for RecyclerView.
After making changes in your build.gradle file, select “Sync now”. After it sync’s successfully we are good to go.
Let’s create an Activity file, right-click on your package name and choose New > Kotlin File/Class. I have named it MainActivity. We will come back to the Activity later. Let us goto the XML file called activity_main and create a RecyclerView under a Relative layout as follows:
The Cells in the RecyclerView also need a layout, let us create one XML file called potato_layout.xml as follows:
A RecyclerView needs an Adapter to layout it’s cell according to the data source passed to it. So let us create a Kotlin Class called PotatoAdapter.kt
Now all we have to do is use the RecyclerView in the Activity. Below is the code of my MainActivity.kt :
Build and run the project, you should see the Potato list app as shown below:
If you’re stuck anywhere, let me know in the comments below. Meanwhile I’m busy doing the Potato dance.