Kotlin RecyclerView Tutorial With Example will be covered here.
RecyclerView is developed with kotlin for your next awesome android app.
This tutorial will guide you how to make a RecyclerView With CardView, Image and Text in Android Kotlin.
You will also learn to implement onClick, onItemClickListener, onItemTouchListener of RecyclerView.
We will use material design to implement RecyclerView and CardView.
RecyclerView and Kotlin both are updated items for android app development. Kotlin is updated from Java and RecyclerView is updated from Listview.
So this tutorial can be handy helpful for you to update with latest trends in android app development.
First, check the output of RecyclerView Android tutorial then follow all the steps.
Step 1. Updating build.gradle(Module:app)
Very first thing is to add two lines in build.gradle(Module:app) file as per below code
compile 'com.android.support:recyclerview-v7:27.1.1' compile 'com.android.support:cardview-v7:27.1.1'
Full source code can be look like
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 27 defaultConfig { applicationId "com.example.parsaniahardik.kotlin_reyclerview" minSdkVersion 15 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' compile 'com.android.support:recyclerview-v7:27.1.1' compile 'com.android.support:cardview-v7:27.1.1' }
Step 2. Downloading Images
We need some images to demonstrate in RecyclerView.
Click here to download images and add them into the drawable folder.
You should learn here how to add images in drawable folder in the step 2 of circular progressbar example android. (No need to create xml file in drawable, just copy and paste images in drawable).
Step 3: Coding cardview.xml
Create a new file into drawable folder
Give it a name cardview.xml
Copy below source code into it.
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true"> <shape android:shape="rectangle"> <padding android:left="4dp" android:top="4dp" android:right="4dp" android:bottom="4dp" /> <gradient android:startColor="#1cb73b" android:endColor="#29ba48" android:angle="270" /> <corners android:topLeftRadius="4dp" android:topRightRadius="4dp"/> </shape> </item> <item android:state_focused="false" > <shape android:shape="rectangle"> <padding android:left="4dp" android:top="4dp" android:right="4dp" android:bottom="4dp" /> <gradient android:startColor="#1cb724" android:endColor="#29ba41" android:angle="270" /> <corners android:topLeftRadius="4dp" android:topRightRadius="4dp" /> </shape> </item> </selector>
This file makes designs how the cardview should look.
You change colors, corner size etc. things in this file.
Step 4. Making Row Item File
Prepare a new layout xml file and give it a name rv_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="16dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="16dp" tools:context=".MainActivity"> <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="0dp" card_view:cardCornerRadius="4dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tv" android:height="40dp" android:background="@drawable/cardview" android:gravity="center_vertical" android:paddingLeft="10dp" android:text="Image" android:textColor="#fff" android:textStyle="bold" android:textSize="18sp" /> <ImageView android:layout_width="80dp" android:layout_height="80dp" android:layout_marginTop="10dp" android:id="@+id/iv" android:layout_marginLeft="10dp" android:src="@drawable/bike"/> </LinearLayout> </android.support.v7.widget.CardView> </RelativeLayout>
This file is the core structure of how single row of recyclerview will be look a like.
It contains ImageView and TextView.
Step 5. Making Model Class
Make a new kotlin class named “Model.kt”
Add below source code into it
class Model { var name: String? = null var image_drawable: Int = 0 fun getNames(): String { return name.toString() } fun setNames(name: String) { this.name = name } fun getImage_drawables(): Int { return image_drawable } fun setImage_drawables(image_drawable: Int) { this.image_drawable = image_drawable } }
Step 6. Custom Adapter
Now we will make a custom adapter. For this, create a new class named Adapter.kt
Write below source code in Adapter class.
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 /** * Created by Parsania Hardik on 26-Jun-17. */ class Adapter(ctx: Context, private val imageModelArrayList: ArrayList<Model>) : RecyclerView.Adapter<Adapter.MyViewHolder>() { private val inflater: LayoutInflater init { inflater = LayoutInflater.from(ctx) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.MyViewHolder { val view = inflater.inflate(R.layout.rv_item, parent, false) return MyViewHolder(view) } override fun onBindViewHolder(holder: Adapter.MyViewHolder, position: Int) { holder.iv.setImageResource(imageModelArrayList[position].getImage_drawables()) 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 } } }
Step 7. Updating Main Activity
We need to change both activity_main.xml and MainActivity.kt files
Replace source code of activity_main.xml with below one
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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="match_parent" android:layout_marginTop="15dp"/> </LinearLayout>
Now replace code of MainActivity.kt class
import android.content.Context import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.GestureDetector import android.view.MotionEvent import android.view.View import android.widget.Toast import java.util.ArrayList class MainActivity : AppCompatActivity() { private var recyclerView: RecyclerView? = null private var imageModelArrayList: ArrayList<Model>? = null private var adapter: Adapter? = null private val myImageList = intArrayOf(R.drawable.benz, R.drawable.bike, R.drawable.car, R.drawable.carrera, R.drawable.ferrari, R.drawable.harly, R.drawable.lamborghini, R.drawable.silver) private val myImageNameList = arrayOf("Benz", "Bike", "Car", "Carrera", "Ferrari", "Harly", "Lamborghini", "Silver") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) recyclerView = findViewById(R.id.recycler) as RecyclerView imageModelArrayList = populateList() Log.d("hjhjh", imageModelArrayList!!.size.toString() + "") adapter = Adapter(this, imageModelArrayList!!) recyclerView!!.adapter = adapter recyclerView!!.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false) recyclerView!!.addOnItemTouchListener(RecyclerTouchListener(applicationContext, recyclerView!!, object : ClickListener { override fun onClick(view: View, position: Int) { Toast.makeText(this@MainActivity, imageModelArrayList!![position].getNames(), Toast.LENGTH_SHORT).show() } override fun onLongClick(view: View?, position: Int) { } })) } private fun populateList(): ArrayList<Model> { val list = ArrayList<Model>() for (i in 0..7) { val imageModel = Model() imageModel.setNames(myImageNameList[i]) imageModel.setImage_drawables(myImageList[i]) list.add(imageModel) } return list } interface ClickListener { fun onClick(view: View, position: Int) fun onLongClick(view: View?, position: Int) } internal class RecyclerTouchListener(context: Context, recyclerView: RecyclerView, private val clickListener: ClickListener?) : RecyclerView.OnItemTouchListener { private val gestureDetector: GestureDetector init { gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapUp(e: MotionEvent): Boolean { return true } override fun onLongPress(e: MotionEvent) { val child = recyclerView.findChildViewUnder(e.x, e.y) if (child != null && clickListener != null) { clickListener.onLongClick(child, recyclerView.getChildPosition(child)) } } }) } override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { val child = rv.findChildViewUnder(e.x, e.y) if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) { clickListener.onClick(child, rv.getChildPosition(child)) } return false } override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {} override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { } } }
Explaining MainActivity.kt
The below code is required to get click position of RecyclerView.
recyclerView!!.addOnItemTouchListener(RecyclerTouchListener(applicationContext, recyclerView!!, object : ClickListener { override fun onClick(view: View, position: Int) { Toast.makeText(this@MainActivity, imageModelArrayList!![position].getNames(), Toast.LENGTH_SHORT).show() } override fun onLongClick(view: View?, position: Int) { } }))
To get click position, we need create one interface and one class.
Interface is created with following code
interface ClickListener { fun onClick(view: View, position: Int) fun onLongClick(view: View?, position: Int) }
The required class is made with below source code
internal class RecyclerTouchListener(context: Context, recyclerView: RecyclerView, private val clickListener: ClickListener?) : RecyclerView.OnItemTouchListener { private val gestureDetector: GestureDetector init { gestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapUp(e: MotionEvent): Boolean { return true } override fun onLongPress(e: MotionEvent) { val child = recyclerView.findChildViewUnder(e.x, e.y) if (child != null && clickListener != null) { clickListener.onLongClick(child, recyclerView.getChildPosition(child)) } } }) } override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean { val child = rv.findChildViewUnder(e.x, e.y) if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) { clickListener.onClick(child, rv.getChildPosition(child)) } return false } override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {} override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { } }
So it was all about making RecyclerView With CardView, Material Design ,Image And Text in Kotlin for android app.
Do not hesitate to use comment section for any queries or reviews.
Please LIKE and SHARE this kotlin recyclerview tutorial with your other buddies to help them as well as us!
Cheers and happy coding!
Download Source Code for Android Kotlin RecyclerView example
Hit following link to download source code
[sociallocker]Download Kotlin Reyclerview CardView[/sociallocker]