Android RecyclerView Using Kotlin With Example

In this article, we will learn about android RecyclerView using Kotlin. We will go through various example that demonstrates how to use different attributes of RecyclerView. For example,

In this article, we will get answer to questions like –

  • What is RecyclerView?
  • Why should we consider RecyclerView while designing ui for any app?
  • What are possibilities using RecyclerView while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin Android RecyclerView Using Kotlin With Example Output

Getting Started

We can define android RecyclerView widget as below –

RecyclerView is viewGroup that make it easy to efficiently display large set of data.

Now, how do we use RecyclerView in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as RecyclerView. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android RecyclerView Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using RecyclerView in Kotlin

Follow steps below to use RecyclerView in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">RecyclerView</string>
        <string name="animal_image_description">Animal Image Description</string>
    </resources>
    
  • Define UI for single Item

    Now, we need to define view for single item in recyclerView. So, create a new xml file, list_item.xml, in res/layout folder. Then, add below code into it –

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        tools:context=".MainActivity"
        android:background="?android:attr/selectableItemBackground">
    
        <ImageView
            android:id="@+id/image"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:contentDescription="@string/animal_image_description"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            app:layout_constraintStart_toEndOf="@+id/image"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Since we want to show image and name for each item in RecyclerView, we have defined ui accordingly.

  • Define Model for each Item

    In this article, we are going to show List of Animals in RecyclerView using Kotlin. So, we need to define a model class, Animal, to be used in each item object. So, create a new file, Animal.kt, in com.tutorialwing.recyclerview package. Then, add below code in it –

    package com.tutorialwing.recyclerview
    
    class Animal(var name: String, var image: Int, var details: String)
    

    This class will accept

    1. name: It contains name of animal.
    2. image: It contains image of animal.
    3. details: It contains some description of animal.
  • Define Adapter for RecyclerView

    Now, we need to define an adapter that accepts list of animal and provides data to recyclerView. So, create a new file, CustomAdapter.kt, in com.tutorialwing.recyclerview. Then, add below code in it –

    package com.tutorialwing.recyclerview
    
    import android.view.LayoutInflater
    import android.view.ViewGroup
    import androidx.recyclerview.widget.RecyclerView
    import com.tutorialwing.recyclerview.databinding.ListItemBinding
    
    class CustomAdapter(
    	private val animalList: ArrayList<Animal>
    ) :
    	RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
    
    	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    		val v = ListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    		return ViewHolder(v)
    	}
    
    	override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    		holder.bindItem(animalList[position])
    	}
    
    	override fun getItemCount(): Int {
    		return animalList.size
    	}
    
    	class ViewHolder(var listItemBinding: ListItemBinding) :
    		RecyclerView.ViewHolder(listItemBinding.root) {
    		fun bindItem(animal: Animal) {
    			listItemBinding.image.setImageResource(animal.image)
    			listItemBinding.name.text = animal.name
    		}
    	}
    }
    

    Here,

    1. onCreateViewHolder(): This method is called to create a new view for recyclerView. It inflates a new ui from ListItemBinding and return ViewHolder class using this view.
    2. onBindViewHolder(): It is called to bind data to a view present at specified position.
    3. getItemCount(): It is called to get size of items in the recyclerView. Here, it is same as size of animalList.
    4. ViewHolder: ViewHolder class represent one item in RecyclerView. It is inherited from RecyclerView.ViewHolder class. bindItem() method inside this class is called to bind data with view item.
  • Now, we need to define RecyclerView. So, open res/layout/activity_main.xml file. Then, add below code in it –

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="#fefefe"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Here, we have defined RecyclerView in xml file.

  • Now, we need to set adapter, layoutManager etc. to RecyclerView using Kotlin file. So, open kotlin file, MainActivity.kt. Then, add below code in it –

    package com.tutorialwing.recyclerview
    
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import androidx.recyclerview.widget.LinearLayoutManager
    import com.tutorialwing.recyclerview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupRecyclerView()
    	}
    
    	private fun setupRecyclerView() {
    		binding.recyclerView.apply {
    			layoutManager = LinearLayoutManager(context)
    			adapter = CustomAdapter(createAnimalList())
    		}
    	}
    
    	private fun createAnimalList(): ArrayList<Animal> {
    		return arrayListOf<Animal>(
    			Animal(
    				"Antilope",
    				R.drawable.antilope,
    				"Antilope is a genus of bovid that contains a single living species, the blackbuck of South Asia. Two extinct species are also known."
    			),
    			Animal(
    				"Bear",
    				R.drawable.bear,
    				"Bears are carnivoran mammals of the family Ursidae. They are classified as caniforms, or doglike carnivorans. Although only eight species of bears are extant, they are widespread, appearing in a wide variety of habitats throughout the Northern Hemisphere and partially in the Southern Hemisphere"
    			),
    			Animal(
    				"Bison",
    				R.drawable.bison,
    				"Bison are large, even-toed ungulates in the genus Bison within the subfamily Bovinae. Two extant and six extinct species are recognised. Of the six extinct species, five became extinct in the Quaternary extinction event. Bison palaeosinensis evolved in the Early Pleistocene in South Asia, and was the evolutionary ancestor of B. priscus (steppe bison), which was the ancestor of all other Bison species."
    			),
    			Animal(
    				"Buffalo",
    				R.drawable.buffalo,
    				"Buffalo is the second-largest city in the U.S. state of New York and the seat of Erie County. It is at the eastern end of Lake Erie, at the head of the Niagara River, and is next to the Canadian border in southern Ontario. With a population of 278,349 according to the 2020 census, Buffalo is the 76th-largest city in the United States."
    			),
    			Animal(
    				"Camel",
    				R.drawable.camel,
    				"A camel is an even-toed ungulate in the genus Camelus that bears distinctive fatty deposits known as \"humps\" on its back. Camels have long been domesticated and, as livestock, they provide food (milk and meat) and textiles (fiber and felt from hair). Camels are working animals especially suited to their desert habitat and are a vital means of transport for passengers and cargo."
    			),
    			Animal(
    				"Cheetah",
    				R.drawable.cheetah,
    				"The cheetah (Acinonyx jubatus) is a large cat native to Africa and central Iran. It is the fastest land animal, estimated to be capable of running at 80 to 128 km/h (50 to 80 mph) with the fastest reliably recorded speeds being 93 and 98 km/h (58 and 61 mph), and as such has several adaptations for speed, including a light build, long thin legs and a long tail. It typically reaches 67–94 cm (26–37 in) at the shoulder, and the head-and-body length is between 1.1 and 1.5 m (3 ft 7 in and 4 ft 11 in)"
    			),
    			Animal(
    				"Cow",
    				R.drawable.cow,
    				"Cattle, taurine cattle, Eurasian cattle, or European cattle (Bos taurus or Bos primigenius taurus) are large domesticated cloven-hooved herbivores. They are a prominent modern member of the subfamily Bovinae and the most widespread species of the genus Bos."
    			),
    			Animal(
    				"Crocodile",
    				R.drawable.crocodile,
    				"Crocodiles (family Crocodylidae) or true crocodiles are large semiaquatic reptiles that live throughout the tropics in Africa, Asia, the Americas and Australia. The term crocodile is sometimes used even more loosely to include all extant members of the order Crocodilia, which includes the alligators and caimans (family Alligatoridae), the gharial and false gharial (family Gavialidae), and all other living and fossil Crocodylomorpha."
    			),
    			Animal(
    				"Deer",
    				R.drawable.deer,
    				"Deer or true deer are hoofed ruminant mammals forming the family Cervidae. The two main groups of deer are the Cervinae, including the muntjac, the elk (wapiti), the red deer, and the fallow deer; and the Capreolinae, including the reindeer (caribou), white-tailed deer, the roe deer, and the moose"
    			),
    			Animal(
    				"Elephant",
    				R.drawable.elephant,
    				"Elephants are the largest existing land animals. Three living species are currently recognised: the African bush elephant, the African forest elephant, and the Asian elephant. They are an informal grouping within the proboscidean family Elephantidae."
    			),
    			Animal(
    				"Fox",
    				R.drawable.fox,
    				"Foxes are small to medium-sized, omnivorous mammals belonging to several genera of the family Canidae. They have a flattened skull, upright triangular ears, a pointed, slightly upturned snout, and a long bushy tail. Twelve species belong to the monophyletic \"true foxes\" group of genus Vulpes."
    			),
    			Animal(
    				"Giraffe",
    				R.drawable.giraffe,
    				"The giraffe is a tall African mammal belonging to the genus Giraffa. Specifically, It is an even-toed ungulate. It is the tallest living terrestrial animal and the largest ruminant on Earth. Traditionally, giraffes were thought to be one species, Giraffa camelopardalis, with nine subspecies."
    			),
    			Animal(
    				"Goat",
    				R.drawable.goat,
    				"The mountain goat (Oreamnos americanus), also known as the Rocky Mountain goat, is a hoofed mammal endemic to mountainous areas of western North America. A subalpine to alpine species, it is a sure-footed climber commonly seen on cliffs and ice."
    			),
    			Animal(
    				"Hedgehog",
    				R.drawable.hedgehog,
    				"A hedgehog is a spiny mammal of the subfamily Erinaceinae, in the eulipotyphlan family Erinaceidae. There are seventeen species of hedgehog in five genera found throughout parts of Europe, Asia, and Africa, and in New Zealand by introduction."
    			),
    			Animal(
    				"Hippo",
    				R.drawable.hippo,
    				"The hippopotamus, also called the hippo, common hippopotamus or river hippopotamus, is a large, mostly herbivorous, semiaquatic mammal and ungulate native to sub-Saharan Africa. It is one of only two extant species in the family Hippopotamidae, the other being the pygmy hippopotamus"
    			),
    			Animal(
    				"Horse",
    				R.drawable.horse,
    				"The horse is a domesticated one-toed hoofed mammal. It belongs to the taxonomic family Equidae and is one of two extant subspecies of Equus ferus. The horse evolved over the past 45 to 55 million years from Eohippus, a small multi-toed creature, into the large, single-toed animal of today."
    			),
    			Animal(
    				"Hyena",
    				R.drawable.hyena,
    				"Hyenas, or hyaenas, are feliform carnivoran mammals of the family Hyaenidae. With only four extant species, it is the fifth-smallest biological family in the Carnivora and one of the smallest in the class Mammalia. Despite their low diversity, hyenas are unique and vital components of most African ecosystems."
    			),
    			Animal(
    				"Jackal",
    				R.drawable.jackal,
    				"Jackals are medium-sized omnivorous mammals of the subtribe Canina, which also includes wolves and the domestic dog, among other species."
    			),
    			Animal(
    				"Kangaroo",
    				R.drawable.kangaroo,
    				"The kangaroo is a marsupial from the family Macropodidae. In common use the term is used to describe the largest species from this family, the red kangaroo, as well as the antilopine kangaroo, eastern grey kangaroo, and western grey kangaroo. Kangaroos are indigenous to Australia and New Guinea."
    			),
    			Animal(
    				"Koala",
    				R.drawable.koala,
    				"The koala or, inaccurately, koala bear, is an arboreal herbivorous marsupial native to Australia. It is the only extant representative of the family Phascolarctidae and its closest living relatives are the wombats, which are members of the family Vombatidae."
    			),
    			Animal(
    				"Lion",
    				R.drawable.lion,
    				"The lion is a large cat of the genus Panthera native to Africa and India. It has a muscular, deep-chested body, short, rounded head, round ears, and a hairy tuft at the end of its tail. It is sexually dimorphic; adult male lions are larger than females and have a prominent mane."
    			),
    			Animal(
    				"Monkey",
    				R.drawable.monkey,
    				"Monkey is a common name that may refer to most mammals of the infraorder Simiiformes, also known as the simians. "
    			),
    			Animal(
    				"Panda",
    				R.drawable.panda,
    				"The giant panda, also known as the panda bear, is a bear native to South Central China. It is characterised by its bold black-and-white coat and rotund body. The name \"giant panda\" is sometimes used to distinguish it from the red panda, a neighboring musteloid."
    			),
    			Animal(
    				"Panther",
    				R.drawable.panther,
    				"A black panther is the melanistic colour variant of the leopard and the jaguar. Black panthers of both species have excess black pigments, but their typical rosettes are also present."
    			),
    			Animal(
    				"Porcupine",
    				R.drawable.porcupine,
    				"Porcupines are large rodents with coats of sharp spines, or quills, that protect them against predation. The term covers two families of animals: the Old World porcupines of family Hystricidae, and the New World porcupines of family Erethizontidae."
    			),
    			Animal(
    				"Rabbit",
    				R.drawable.rabbit,
    				"Rabbits, also known as bunnies or bunny rabbits, are small mammals in the family Leporidae (along with the hare) of the order Lagomorpha (along with the pika). Oryctolagus cuniculus includes the European rabbit species and its descendants, the world's 305 breeds[1] of domestic rabbit. Sylvilagus includes 13 wild rabbit species, among them the seven types of cottontail."
    			),
    			Animal(
    				"Racoon",
    				R.drawable.racoon,
    				"The raccoon, sometimes called the common raccoon to distinguish it from other species, is a medium-sized mammal native to North America. It is the largest of the procyonid family, having a body length of 40 to 70 cm, and a body weight of 5 to 26 kg."
    			),
    			Animal(
    				"Rhino",
    				R.drawable.rhino,
    				"A rhinoceros, commonly abbreviated to rhino, is a member of any of the five extant species of odd-toed ungulates in the family Rhinocerotidae. Two of the extant species are native to Africa, and three to South and Southeast Asia."
    			),
    			Animal(
    				"Squirrel",
    				R.drawable.squirrel,
    				"Squirrels are members of the family Sciuridae, a family that includes small or medium-size rodents. The squirrel family includes tree squirrels, ground squirrels, chipmunks, marmots, flying squirrels, and prairie dogs amongst other rodents."
    			),
    			Animal(
    				"Stag",
    				R.drawable.stag,
    				"Deer or true deer are hoofed ruminant mammals forming the family Cervidae. The two main groups of deer are the Cervinae, including the muntjac, the elk (wapiti), the red deer, and the fallow deer; and the Capreolinae, including the reindeer (caribou), white-tailed deer, the roe deer, and the moose."
    			),
    			Animal(
    				"Tiger",
    				R.drawable.tiger,
    				"The tiger is the largest living cat species and a member of the genus Panthera. It is most recognisable for its dark vertical stripes on orange fur with a white underside. An apex predator, it primarily preys on ungulates such as deer and wild boar."
    			),
    			Animal(
    				"Zebra",
    				R.drawable.zebra,
    				"Zebras are African equines with distinctive black-and-white striped coats. There are three living species: the Grévy's zebra, plains zebra, and the mountain zebra. Zebras share the genus Equus with horses and asses, the three groups being the only living members of the family Equidae."
    			)
    		)
    	}
    }
    

    Here,

    1. setupRecyclerView(): Inside this method, we set layoutManager and adapter to recyclerView.
    2. createAnimalList(): Inside this method, we create data for recyclerView. Here, we create list of Animal by using their name, image and description.

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android RecyclerView Using Kotlin With Example Output

Add Divider in RecyclerView Using Kotlin

Notice that there is no gap or any kind of divider between items in RecyclerView. Now, question is how do we add divider in RecyclerView using Kotlin ?

Follow steps below to get answer –

  1. Create a drawable file

    At first, we need to create a drawable file, divider.xml, in res/drawable folder. Then, add below code in it –

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <size
            android:width="1dp"
            android:height="1dp" />
        <solid android:color="#f0f0f0" />
    </shape>
    
  2. Now, we need to create a subclass of RecyclerView.ItemDecoration to customise how we want to decorate item in recyclerView. So, create a new file, RecyclerViewItemDecoration.kt, in
    com.tutorialwing.recyclerview package. Then, add below code in it –

    package com.tutorialwing.recyclerview
    
    import android.content.Context
    import android.graphics.Canvas
    import android.graphics.drawable.Drawable
    import android.view.View
    import androidx.core.content.ContextCompat
    import androidx.recyclerview.widget.RecyclerView
    
    class RecyclerViewItemDecoration(
    	context: Context,
    	resId: Int
    ) : RecyclerView.ItemDecoration() {
    
    	private var mDivider: Drawable = ContextCompat.getDrawable(context, resId)!!
    
    	override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    		super.onDraw(c, parent, state)
    
    		val dividerLeftMargin: Int = 2
    
    		val dividerRightMargin: Int = parent.width - 2
    
    		for (i in 0 until parent.childCount) {
    
    			// Check if it is not first and last items in the list.
    			if (i != parent.childCount - 1) {
    				val child: View = parent.getChildAt(i)
    
    				val params = child.layoutParams as RecyclerView.LayoutParams
    
    				val dividerTop: Int = child.bottom + params.bottomMargin
    				val dividerBottom: Int = dividerTop + mDivider.intrinsicHeight
    
    				mDivider.setBounds(dividerLeftMargin, dividerTop, dividerRightMargin, dividerBottom)
    				mDivider.draw(c)
    			}
    		}
    	}
    }
    
  3. Now, we have to set this item decorator to our recyclerView using Kotlin in this project. So, open MainActivity.kt file. Then, add below lines of code inside setupRecyclerView() method. –
    addItemDecoration(RecyclerViewItemDecoration(context, R.drawable.divider))
    

    Finally, this method will be like –

    private fun setupRecyclerView() {
    	binding.recyclerView.apply {
    		layoutManager = LinearLayoutManager(context)
    		adapter = CustomAdapter(createAnimalList())
    		addItemDecoration(RecyclerViewItemDecoration(context, R.drawable.divider))
    	}
    }
    
  4. Now, run application. We will get output as below –
    Tutorialwing Kotlin Android RecyclerView Using Kotlin With Example

Add Item Click Listener in RecyclerView Using Kotlin

Till now, we have displayed items in RecyclerView with dividers using RecyclerView.ItemDecoration. Now, what if we want to perform some operation when item is clicked. How do we do perform item click in recyclerView ?

Follow steps below to handle item click in recyclerView using Kotlin –

  1. Add another parameter, private val listener: (Animal, Int) -> Unit in CustomAdapter.kt file.
  2. Inside CustomerAdapter.kt, add click listener of itemView for ViewHolder inside onBindViewHolderonBindViewHolder method –
    holder.itemView.setOnClickListener { listener(animalList[position], position) }
    

    Finally, code inside CustomAdapter.kt file is –

    package com.tutorialwing.recyclerview
    
    import android.view.LayoutInflater
    import android.view.ViewGroup
    import androidx.recyclerview.widget.RecyclerView
    import com.tutorialwing.recyclerview.databinding.ListItemBinding
    
    class CustomAdapter(
    	private val animalList: ArrayList<Animal>,
    	private val listener: (Animal, Int) -> Unit
    ) :
    	RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
    
    	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    		val v = ListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    		return ViewHolder(v)
    	}
    
    	override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    		holder.bindItem(animalList[position])
    		holder.itemView.setOnClickListener { listener(animalList[position], position) }
    	}
    
    	override fun getItemCount(): Int {
    		return animalList.size
    	}
    
    	class ViewHolder(var listItemBinding: ListItemBinding) :
    		RecyclerView.ViewHolder(listItemBinding.root) {
    		fun bindItem(animal: Animal) {
    			listItemBinding.image.setImageResource(animal.image)
    			listItemBinding.name.text = animal.name
    		}
    	}
    }
    
  3. Now, open MainActivity.kt file and modify code where we have created instance of CustomAdapter class as below –
    adapter = CustomAdapter(createAnimalList()) { animal, position ->
    	Toast.makeText(
    		this@MainActivity,
    		"Clicked on animal: ${animal.name}",
    		Toast.LENGTH_SHORT
    	).show()
    }
    

    Here, we have added a Toast message to displayed whenever any item is clicked inside recyclerView.

    Finally, code inside MainActivity.kt file is –

    package com.tutorialwing.recyclerview
    
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import androidx.recyclerview.widget.LinearLayoutManager
    import com.tutorialwing.recyclerview.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupRecyclerView()
    	}
    
    	private fun setupRecyclerView() {
    		binding.recyclerView.apply {
    			layoutManager = LinearLayoutManager(context)
    			adapter = CustomAdapter(createAnimalList()) { animal, position ->
    				Toast.makeText(
    					this@MainActivity,
    					"Clicked on animal: ${animal.name}",
    					Toast.LENGTH_SHORT
    				).show()
    			}
    			addItemDecoration(RecyclerViewItemDecoration(context, R.drawable.divider))
    		}
    	}
    
    	private fun createAnimalList(): ArrayList<Animal> {
    		// OTHER CODE to create list of animals.
    	}
    }
    
  4. Now, run application, we will get output as below –
    Tutorialwing Kotlin Android RecyclerView Using Kotlin With Example Output

Different Attributes of RecyclerView in XML

Now, we will see how to use different attributes of Android RecyclerView using Kotlin to customise it –

Set Id of RecyclerView

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of RecyclerView using android:id attribute like below –

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_ID"
        />

Here, we have set id of RecyclerView as recyclerView_ID using android:id=”” attribute. So, if we need to reference this RecyclerView, we need to use this id – recyclerView_ID.

Set Width of RecyclerView

We use android:layout_width=”” attribute to set width of RecyclerView.
We can do it as below –

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).

Set Height of RecyclerView

We use android:layout_height=”” attribute to set height of RecyclerView.
We can do it as below –

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.

Set Padding of RecyclerView

We use android:padding=”” attribute to set padding of RecyclerView.
We can do it as below –

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in RecyclerView using android:padding=”” attribute.

Set Margin of RecyclerView

We use android:layout_margin=”” attribute to set margin of RecyclerView.
We can do it as below –

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in RecyclerView using android:layout_margin=”” attribute.

Set Background of RecyclerView

We use android:background=”” attribute to set background of RecyclerView.
We can do it as below –

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in RecyclerView using android:background=”” attribute.

Set Visibility of RecyclerView

We use android:visibility=”” attribute to set visibility of RecyclerView.
We can do it as below –

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of RecyclerView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible

Thus, we have seen what is RecyclerView, how can we use android RecyclerView using Kotlin ? etc. We also went through different attributes of android RecyclerView.

Leave a Reply