Looking For Anything Specific?

Android RecyclerView Example With Kotlin Sample Code

Hello everyone, Its good to see you .... write to you all in this new tutorial. Recently I have written a tutorial on how to pass data between fragments which you can learn from below link, In that tutorial, I have used a non recommended way to create a list of buttons yes I recreated every button which is not recommended because the characteristic of the button stays the same. So here is the recommended way to create a list of buttons, text, views any item you want in your android application. Which is by using the Android RecyclerView, You get an overview of the RecyclerView in here Android RecyclerView Overview


RecyclerView Overview: 

If you have read the above tutorial, you might have noticed that I'm was using the same button repeatedly though its okay for a few numbers of buttons, But if you ever wanted to user 20 or 30 buttons its a headache also if you don't know how many of those buttons are going to be there then its definitely a problematic solution, so that's why Android has given us a great solution which called RecyclerView. 

If your app needs to display a scrolling list of elements based on large data sets (or data that frequently changes), you should use RecyclerView as described on this page.

The RecyclerView widget is a more advanced and flexible version of ListView.


Now that we know what RecyclerView is now we can use it in our application. Let's start with a use case, our use case here is to list the android version names like Lolipop, Nougat, Android 10 or 11 like that and assume that we don't know how many of them there actually is. We will list down those names and store it as an array in the strings.xml file later in our application we will list them and show them in a text view.

Kotlin android recyclerview sample code


Before getting into the coding part there are some important things that you need to know about the recycler view, which are, its the same a traditional listview but with more options. For a recycler view to work properly, you need few things to set up before the first one is the Recycler View Adapter, which is the key element of the recycler view that tells our system what layout to use and what data to display. The second thing is the ViewHolder in recycler view a view holder is a layout that you're going to show data it could be a TextView a Button or even a constraint layout with the combination of complex UI widgets that android provides. And at last the layout manager this is also one of the important parts to take note of because as a developer I even forgot sometimes to set the layout manager for the recycler view, so A layout manager is which will help us on how to display the items of the recycler view there are three types in there, LinearLayoutManager, GridLayoutManger and StaggeredGridLayoutManager, but we mostly use only two types LinearLayoutManager and GridLayoutManager. For this tutorial, we are going to stick with LinearLayoutManager.  

How to implement Basic RecyclerView in Android With Kotlin: 

Now we have come to the exciting part, the coding part obviously let's start with Gradle, RecyclerView is a support library so you need to add it to the Gradle, if you're using androidx you can copy the below implementation line onto your app level build.Gradle file and put it inside the dependencies 

    implementation 'androidx.recyclerview:recyclerview:1.1.0'

Note: The version number mentioned here is the stable version available when the time of writing this tutorial. Please refer to the android developers' website for the updated version in the future.

 Bottom Sheet Android With Kotlin

Once you have added the dependencies into the Gradle sync your project and let the android studio do its thing. After successfully synchronized now you will be able to add recycler view into your android project. So now let's start with the XML 


 <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/androidVersionRecycler"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"

        android:orientation="vertical"

        tools:listitem="@layout/recycler_list_view"

        tools:itemCount="10"/>


Above is the code to add a recycler view to your activity's or fragment's layout. It will add the recyclerview and allows us to add some of the common parameters, that we talked about earlier. The first three attributes are simple as they are required for all the android widgets. now let's move on to the fourth one. 

Learn How To Ask Runtime Permission In Android With Kotlin 

How to Store Data In Android With Shared Preference In Kotlin 

app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager", remember earlier we talked about layout managers, A layout manger is what that tells your android system to how to draw the layout either in a linear form or as a grid form. For our requirements, we are going to use LinearLayoutManger. In an earlier version of android development, we used to set the layoutmanager at the runtime instead of setting up this at the XML level. So the advantage of doing this is that it reduces some code in your class file. And improves the performance I guess, because it knows beforehand that it is going to draw in a linear manner or grid manner. And if you wanted to check out other layout managers you can set the layout manager to GridLayoutManager like that Its good to set orientation if you're using Linear Layout Manager, Because in a nutshell what the linear layout manager does is that it will mimic the behavior of Linear Layout so you have to set them as either vertical or horizontal, by default it is set to vertical.

You can also notice that there are two other attributes that are there but with tools namespace, so what these attributes do is it will only show up in the android studio and will not be used in our application at runtime. Though it is useful in our case, mostly when you're using recycler views you can set the view holder's layout and the count for them. In the above code We have set the list item as a layout and item count as 10 meaning it will show 10-row items of the given layout in the android studio only.

Once you have added the recycler view widget to your XML layout now create a new XML layout file to design the row item, A row item is nothing but a single element in your list. For out learning purpose we are going to use a single textview with layout that will show a list of names. 

<?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"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    xmlns:tools="http://schemas.android.com/tools">


    <TextView

        android:id="@+id/versionNames"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:padding="16dp"

        android:textAppearance="@style/TextAppearance.AppCompat.Large"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintTop_toTopOf="parent"

        tools:text="Android" />

</androidx.constraintlayout.widget.ConstraintLayout>


Above is the code for a simple textview with android's constraint layout, you can refer this tutorial here -> How to customize android textview to make some interesting design to your textview, but we are going to stick with a simple text view for now. Also, refer here for some best tricks you can use in your constraint layout. Now that we have set up the basic foundation for our android's recycler view, its time to really implement the recycler view by adding the core of the android recycler view's like the adapter and view holder.


Android RecyclerView Adapter:

RecyclerView adapter is the important thing for a recycler view because if you run your code now without setting an adapter you will get an error saying "No adapter attached. Skipping layout.". We are not going to do that.  Below is the step by step instructions on how to create an adapter for android recycler view in kotlin

Create RecyclerView Adapter in Kotlin:

  • Right, Click on the package name "com.example.yourApplication"
  • New -> Kotlin/File Class
  • Enter filename "AndroidVersionRecyclerAdapter" 
  • Hit "Enter"

Note: It's a good practice to always end the name with the functionality of the file like Activity or Fragment, or in our case Adapter because it is going to serve the purpose of an adapter.

And again use the above steps to create a new class file and name it AndroidVersionRecyclerViewHolder for our view holder you can refer to the below screenshot for how the file structure after creating these files.

android recyclerview complete tutorial


Make your class file extend the RecyclerView.Adapter class like below 

class AndroidVersionRecyclerAdapter()  :RecyclerView.Adapter<AndroidVersionRecyclerViewHolder>() {

}

You can see that we have passed one type of argument to the adapter as AndroidVersionRecyclerViewHolder which is our view holder, where we get the layout and display and do all view related actions there.


Now create another class with our view holder name as AndroidVersionRecyclerViewHolder and extend it with RecyclerView.ViewHolder

class AndroidVersionRecyclerViewHolder(view: View): RecyclerView.ViewHolder(view){}

This class will require a parameter that is going to be our view of where we are going to show the data.

Now get back to our adapter class, After extending RecyclerView.Adapter with a ViewHolder class now you need to override three functions which are very fundamental for an android recycler view.

The first function is onCreateViewHolder, this is where everything begins, then you create an object for your recycler view adapter class this will be called. In here, you will do nothing more than creating the view holder which in our case is the newly created layout. You see that this function returns a ViewHolder which is actually the view holder of our own class from AndroidVersionRecyclerViewHolder

 override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): AndroidVersionRecyclerViewHolder

In the above function, it has two parameters which are the parent view group and the type as int, the first parameter will tell us what is the root of this layout and the second will tell us the type, we can discuss about type in later in a new post, lets just on the parent: ViewGroup here. In order to return our ViewHolder class, we need to supply a view which in fact is our textview layout an easy way to do that is to use layout inflater like below        

override fun onCreateViewHolder(

            parent: ViewGroup,

            viewType: Int

        ): AndroidVersionRecyclerViewHolder {

        return  AndroidVersionRecyclerViewHolder(

LayoutInflater.from(parent.context).inflate(R.layout.recycler_list_view,parent,false))

    }

In the above code, we use LayoutInflater to inflate the layout to our view holder, and we get the context from the parent. And in for the inflate method we need to pass three parameters which are the actual layout, parent, and attachToRoot as boolean, so the layout will the recycler list view and we get the parent from the function and attachToRoot is always set to false.

The second function that we need to override is the getItemCount this function will help us to render any number of items we want, In general, it is always the size of our data set. So ou can see that I have used the size of the versionList earlier which I have sent through the constructor.

override fun getItemCount(): Int  = versionList.size 

And the third function is to override the onBindViewHolder, so this is one of the main function in the adapter where all the binding happens, so what this function does is that it will be called every time when a new item is visible to the user, and we want to change some data or make an action in one of the row item.,

override fun onBindViewHolder(holder:ViewHolder, position: Int) {}


So this is where we have to put everything that is related to our data or view like that, To make it easier for us this function holds an instance of the view holder for a single row item which will make it easier to access and manipulate data. So we use that instance to pass the data to our view holder and we can decide what and where to display the data 


override fun onBindViewHolder(holder:AndroidVersionRecyclerViewHolder, position: Int) {

        holder.bind(position,versionList[position],recyclerViewClickListener) 

}

 

In the above code, I simply pass the position, version name as a string, and a click listener learn how to implement android recycler view click listener , so this will be called every time when we want to render/show a new item to the view. So our work here is done now we can move on to the view holder class. 


class AndroidVersionRecyclerViewHolder(view: View): RecyclerView.ViewHolder(view){

 

You can see that our view holder class has one parameter as view, which is the view that we inflated earlier when creating this class. So from here only we can acess the view's inside the layout .Like below 


val nameTextView = view.findViewById<TextView>(R.id.versionNames)  

 

Now that we have out text view we can create a new function named bind with with three arguments to display data as we have already mentioned in the onBindViewHolder ,


fun bind(position:Int,versionName:String,recyclerViewClickListener: RecyclerViewClickListener){

        nameTextView.text = versionName

    }

 

Everything is created and set for a simple recycler view now we have to go to our activity class and then create the adapter and set it to the recycler view Like below,


val androidVersionRecycler = findViewById<RecyclerView>(R.id.androidVersionRecycler)

        androidVersionRecycler.adapter = AndroidVersionRecyclerAdapter(resources.getStringArray(R.array.anroid_names),this)


So while creating an object for the adapter itself passing the data and a click listener to the constructor where the first parameter is the data that we want to show in the screen and we will discuss later the click listener. Update : Learn How to implement android click listerner to a recyclerview row item  It is a good practice to put your array in the string file itself so that you can easily manage it. Everything is set now hit Run.

andorid recyclerview click lister

Voila, you have successfully created and run your android application for RecyclerView, the above gif is from our next post on how to make click actions in the android recyclerview.

Below you can learn how to implement click listener for recyclerview item :


You can get the complete code from GitHub: https://github.com/blackzshaik/BasicRecyclerView

Thanks for spending your valuable time to read and learn. I know my writing is a little shabby, But I still constantly updating my writing style and everything, so feel free to correct me if I'm wrong.


!!!SPREAD THE WORD!!!


keywords:

android recyclervierw tutorial kotlin 

how to create recyclerview adapter with kotlin in andorid

android recyvlerview

recyclerview kotlin

recyclerview in androidx

simple recyclerview android example

recyclerview kotlin example