HOW TO CREATE RECYCLE VIEW IN KOTLIN ANDROID

Taufik Fadlurahman Fajari
3 min readFeb 28, 2021

What is recyle view? recycle view is a place to display the collection of our data as efficient as possible. recycle view make it easy to display the data even we have a lot of data to display, we don’t have to write the long code in xml.

in this tutorial, i want to show you how to create recycle view contain list of food and price.

  • First, create your own project
  • copy library Recycle View from developer.android.com or you can click here
implementation "androidx.recyclerview:recyclerview:1.1.0"

add that library to build.gradle in module app

dependencies {    ...
implementation "androidx.recyclerview:recyclerview:1.1.0"

}

don’t forget to click “Sync Now” in the top right of your code

  • Open activity_main.xml and change your code into code below

and the the design should change like image below

  • Create the new xml file for every item data that we want to display

right click in folder layout and select Layout Resource File and give it the name “item_view.xml” or whatever you want

in this tutorial we just want to display food names and the price, therefore we just need 2 TextView within Linear Layout

change your code like code below

that code will change the display into like image below

  • back to main_activity.xml and add :
tools:listitem="@layout/item_view"

within the recycle view, it means that layout we created in item_view.xml, we want to put in that recycle view. the design will change into like this image below

  • create kotlin class within main package

this code means it is a place to put a list of your data of foods name and also the price

  • Create new class for Adapter

Adapter is used to create every item and to put into viewholder

after you change code like the image above, you will find the class name will have red underline. just put your type or pointer in Adapter and click “Alt + Enter “ for windows just like image below

click implement member, and block all of the suggestion and click add

your code will change into like this

  • at function onCreateViewHolder, this is used to call the methode every time we need to create view holder. you can change your code into like this
  • at function onBindViewHolder, this is used to put our data into the layout so we can display the data we want to show perfectly
  • at function getItemCount, this is used to get the amount of data we want to create
  • go back to MainActivity.kt and change your code into like this

and we already able to create Recycle View with 3 data of Food, the design will be like this image below

for the all code you can just click here

thank you, just comment if i doing any mistake so i can learn for the future

--

--