Read about Kotlin Horizontal RecyclerView With CardView and Image example.
In this tutorial, we will create horizontal recycler view.
Generally, recycler view helps us to show the data in tabular manner and it is vertical mostly.
But sometimes we need to show items horizontally, this is where horizontal recycler view helps us.
There is one in built method in the android system which converts vertical recycler view into the horizontal one.
Let us checkout the below video how horizontal recycler view looks like.
Now follow all the below steps to make a horizontal recycler view.
Add Gradle Lines
Make a new android studio project with “Empty activity” and Kotlin as the source language.
In your new project, open the build.gradle(Module:app) file.
In this file, add the below lines
implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.android.support:cardview-v7:28.0.0'
Android system do not have any built in UI widget to represent Recycler view or Cardview.
So we need to use them externally. For this we should integrate both of them in gradle file.
First line is integrating the Reycler view classes in our project.
Similarly, second line will help us to use the Card view in our project.
Model Methods
Now let us make a class which will work as the data management tool for recycler view.
Make a new Kotlin file and set it’s name as FruitModel.kt
FruitModel.kt should contain the following source snippet
class FruitModel { private var name: String? = null private var image_drawable: Int = 0 fun getNames(): String { return name.toString() } fun setNames(name: String) { this.name = name } fun getImage_drawable(): Int { return image_drawable } fun setImage_drawable(image_drawable: Int) { this.image_drawable = image_drawable } }
There are two variables in the above file.
One is the string variable (name) and another is integer variable (image_drawable) .
Every Child row of our Recycler view will contain one text view and one image view.
So, string variable (name) set data in text view while integer variable (image_drawable) will preview the image in the image view.
Getter and setter methods in the above file will help us to put values in text view as well as in image view.
Fruit Images
Our recycler view rows are showing one fruit image.
For this, we need to have some sample images in our project.
So click on the below link to download some images of fruits.
http://demonuts.com/wp-content/uploads/2018/09/fruit.zip
After downloading the images, save these fruit images inside the app->res->drawable folder.
XML For Child Row
Go to the app->res->layout directory, and make a new XML file named “recycler_item.xml“
Write down the following source snippet in “recycler_item.xml” file.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:padding="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <android.support.v7.widget.CardView android:id="@+id/card_view" android:layout_width="wrap_content" android:layout_height="wrap_content" app:cardCornerRadius="5dp" android:layout_margin="5dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:orientation="vertical"> <ImageView android:layout_width="80dp" android:layout_height="80dp" android:src="@drawable/apple" android:scaleType="fitXY" android:id="@+id/iv" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tv" android:gravity="center" android:text="Image" android:textColor="#000" android:textSize="18sp" /> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout>
Above file will help us to create the look and feel of the each row of recycler view.
You can see that I have added one text view and one image view in the above file.
Both these widgets are under the card view. So it will create card view design.
Adapter For Fruits
Now make a new Kotlin class with name as FruitAdapter.kt
Inside this FruitAdapter.kt class, write the following coding lines
import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import java.util.ArrayList class FruitAdapter(ctx: Context, private val imageModelArrayList: ArrayList<FruitModel>) : RecyclerView.Adapter<FruitAdapter.MyViewHolder>() { private val inflater: LayoutInflater init { inflater = LayoutInflater.from(ctx) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FruitAdapter.MyViewHolder { val view = inflater.inflate(R.layout.recycler_item, parent, false) return MyViewHolder(view) } override fun onBindViewHolder(holder: FruitAdapter.MyViewHolder, position: Int) { holder.iv.setImageResource(imageModelArrayList[position].getImage_drawable()) holder.time.setText(imageModelArrayList[position].getNames()) } override fun getItemCount(): Int { return imageModelArrayList.size } inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var time: TextView var iv: ImageView init { time = itemView.findViewById(R.id.tv) as TextView iv = itemView.findViewById(R.id.iv) as ImageView } } }
Now in the above file, look at the onCreateViewHolder() method.
This method is inflating the recycler_item.xml file. Thus, it will create layout for each child row using this file.
Now read the onBindViewHolder() method in the above code.
Inside this method, compiler will set the text value in the text view and it will provide image reference in the integer format to the image view.
For this purpose, compiler is using imageModelArrayList as the data source.
We will create this data source in the main activity kotlin file.
Last Writing
Now you should have two main files : MainActivity.kt and activity_main.xml
Inside your activity_main.xml file, write down the following code lines
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginTop="15dp" tools:ignore="MissingConstraints"/> </android.support.constraint.ConstraintLayout>
Main layout of our project is containing just one Recycler view.
Now open your MainActivity.kt file and give it below coding snippet
import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import java.util.ArrayList class MainActivity : AppCompatActivity() { private var recyclerView: RecyclerView? = null private var imageModelArrayList: ArrayList<FruitModel>? = null private var adapter: FruitAdapter? = null private val myImageList = intArrayOf( R.drawable.apple, R.drawable.mango, R.drawable.straw, R.drawable.pineapple, R.drawable.orange, R.drawable.blue, R.drawable.water ) private val myImageNameList = arrayOf("Apple", "Mango", "Strawberry", "Pineapple", "Orange", "Blueberry", "Watermelon") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) recyclerView = findViewById(R.id.recycler) as RecyclerView imageModelArrayList = eatFruits() adapter = FruitAdapter(this, imageModelArrayList!!) recyclerView!!.adapter = adapter recyclerView!!.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.HORIZONTAL, false) } private fun eatFruits(): ArrayList<FruitModel> { val list = ArrayList<FruitModel>() for (i in 0..6) { val fruitModel = FruitModel() fruitModel.setNames(myImageNameList[i]) fruitModel.setImage_drawable(myImageList[i]) list.add(fruitModel) } return list } }
Now read the following three coding lines
private var recyclerView: RecyclerView? = null private var imageModelArrayList: ArrayList<FruitModel>? = null private var adapter: FruitAdapter? = null
First line is creating an object of the RecyclerView class.
Second line is making an arraylist (imageModelArrayList) which will hold the objects of the FruitModel.kt class.
This arraylist (imageModelArrayList) will work as the data source.
Third line is making an object of the FruitAdapter.kt class.
Now look at the following source codes
private val myImageList = intArrayOf( R.drawable.apple, R.drawable.mango, R.drawable.straw, R.drawable.pineapple, R.drawable.orange, R.drawable.blue, R.drawable.water ) private val myImageNameList = arrayOf("Apple", "Mango", "Strawberry", "Pineapple", "Orange", "Blueberry", "Watermelon")
There are two variables in the above snippet.
First one is the integer array (myImageList). This myImageList variable holds the reference to the fruit images which we have stored in the drawable folder.
Second variable is the string array (myImageNameList) which have values as the fruit names in the string format.
Now look at the below code of eatFruits() method.
private fun eatFruits(): ArrayList<FruitModel> { val list = ArrayList<FruitModel>() for (i in 0..6) { val fruitModel = FruitModel() fruitModel.setNames(myImageNameList[i]) fruitModel.setImage_drawable(myImageList[i]) list.add(fruitModel) } return list }
Above method creating our data source. It will create one for loop.
Inside every iteration, compiler will create one object of the FruitModel.kt class and then it will assign the fruit name and “fruit image reference to the drawable folder” to this object.
Then it will add this object to the arraylist called “list“
Now look at the following lines
imageModelArrayList = eatFruits() adapter = FruitAdapter(this, imageModelArrayList!!) recyclerView!!.adapter = adapter recyclerView!!.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.HORIZONTAL, false)
First line will execute the eatFruits() method and it will fill the data inside the imageModelArrayList which is our data source.
Then compiler will initialize the object of the FruitAdapter class with data source imageModelArrayList.
After this, compiler will set or attach the adapter to the Recycler view.
Last line will convert the traditional vertical recycler view into the Horizontal Recycler View.