![]() |
VOOZH | about |
In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ability to reuse its views. In RecyclerView when the View goes out of the screen or not visible to the user it won't destroy it, it will reuse these views. This feature helps in reducing power consumption and providing more responsiveness to the application. Now let's see how to implement RecyclerView using Kotlin.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Add RecyclerView to activity_main.xml you can add it from the drag and drop from the design section or you can add it manually by writing some initial characters of RecyclerView then the IDE will give you suggestions for RecyclerView then select RecyclerView it will automatically add it to your layout file.
activity_main.xml:
Now create a new Layout Resource File which will be used to design our CardView layout. Go to app > res > layout > [right-click] > New > Layout Resource File and name that file as card_view_design and add the code provided below. In this file, you can design the layout to show it into the RecyclerView.
card_view_design.xml:
Go to app > java > {package name} > [right-click] > New > Kotlin class/file and choose Data class from the list. Name that file as Item and then click on OK. This file will hold the information of every item which you want to show in your RecyclerView.
Item.kt:
Go to app > java > {package-name} > [right-click] > New > Kotlin class/file and name that file as Adapter and then click on OK. After this add the code provided below. Comments are added inside the code to understand the code in more detail.
This class contains some important functions to work with the RecyclerView these are as follows:
Adapter.kt:
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
MainActivity.kt: