Android Horizontal RecyclerView in Kotlin With Example

This article is next part of our article on Android RecyclerView in Kotlin where we have discussed how to show large set of data in vertically scrollable view. In this article, we will discuss about how to display large set of data in horizontally scrollable view using Kotlin i.e. how to implement android horizontal recyclerView in kotlin.

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

Output

Tutorialwing Kotlin Android Horizontal Recyclerview in Kotlin With Example

Getting Started

We can customize layoutManager of recyclerView to display data in horizontally scrollable way. Follow steps to do it –

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 RecyclerViewHorizontal. 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">RecyclerViewHorizontal</string>
        <string name="hero_image_description">Hero Image Description</string>
    </resources>
    
  • Create Data Model

    In our article, we are going to display list of actors in recyclerView. So, at first, we need to create a new class, Hero.kt, in com.tutorialwing.recyclerviewhorizontal package. Then, add below code in it –

    package com.tutorialwing.recyclerviewhorizontal
    
    class Hero(var name: String, var image: Int)
    

    For each hero, we are storing name and image. So, we have created class accordingly.

  • Create UI for Single Item

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

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.cardview.widget.CardView 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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp">
    
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?android:attr/selectableItemBackground"
            tools:context=".MainActivity">
    
            <ImageView
                android:id="@+id/image"
                android:layout_width="120dp"
                android:layout_height="120dp"
                android:contentDescription="@string/hero_image_description"
                app:layout_constraintEnd_toEndOf="parent"
                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_marginTop="10dp"
                android:padding="3dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/image" />
    
        </androidx.constraintlayout.widget.ConstraintLayout>
    
    </androidx.cardview.widget.CardView>
    
  • Create Adapter For RecyclerView

    Now, we need to create an adapter for recyclerView that provides data to it. So, create new file, CustomAdapter.kt, in com.tutorialwing.recyclerviewhorizontal package. Then, add below code it –

    package com.tutorialwing.recyclerviewhorizontal
    
    import android.view.LayoutInflater
    import android.view.ViewGroup
    import androidx.recyclerview.widget.RecyclerView
    import com.tutorialwing.recyclerviewhorizontal.databinding.ItemBinding
    
    class CustomAdapter(
    	private val heroList: ArrayList<Hero>,
    	private val listener: (Hero, Int) -> Unit
    ) :
    	RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
    
    	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    		val v = ItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    		return ViewHolder(v)
    	}
    
    	override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    		holder.bindItem(heroList[position])
    		holder.itemView.setOnClickListener { listener(heroList[position], position) }
    	}
    
    	override fun getItemCount(): Int {
    		return heroList.size
    	}
    
    	class ViewHolder(var itemBinding: ItemBinding) :
    		RecyclerView.ViewHolder(itemBinding.root) {
    		fun bindItem(hero: Hero) {
    			itemBinding.image.setImageResource(hero.image)
    			itemBinding.name.text = hero.name
    		}
    	}
    }
    
  • 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"
            android:orientation="horizontal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Now, we need to access recyclerView in Kotlin file and set adapter and layoutManager to it. So, open MainActivity.kt and add below code in it –

    package com.tutorialwing.recyclerviewhorizontal
    
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import androidx.recyclerview.widget.LinearLayoutManager
    import com.tutorialwing.recyclerviewhorizontal.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, LinearLayoutManager.HORIZONTAL, false)
    			adapter = CustomAdapter(createHeroList()) { hero, position ->
    				Toast.makeText(
    					this@MainActivity,
    					"Clicked on actor: ${hero.name}",
    					Toast.LENGTH_SHORT
    				).show()
    			}
    		}
    	}
    
    	private fun createHeroList(): ArrayList<Hero> {
    		return arrayListOf<Hero>(
    			Hero(
    				"Ajay Devgan",
    				R.drawable.ajay
    			),
    			Hero(
    				"Chris Hemsworth",
    				R.drawable.chris_hemsworth
    			),
    			Hero(
    				"Daniel Craig",
    				R.drawable.daniel_craig
    			),
    			Hero(
    				"Dwayne Johnson",
    				R.drawable.dwayne_johnson
    			),
    			Hero(
    				"Tom Hiddlestone",
    				R.drawable.tom_hiddleston
    			),
    			Hero(
    				"Tony Stark",
    				R.drawable.tony_stark
    			)
    		)
    	}
    }
    

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android Horizontal Recyclerview in Kotlin With Example

That’s end of our tutorial on Android Horizontal RecyclerView in Kotlin.

Leave a Reply