Wednesday , September 15 2021

Kotlin RecyclerView Example – Building a RecyclerView with Kotlin – Android Coding by DMTechnolab

Learn how to create RecyclerView using Kotlin Kotlin RecyclerView Example. Learning the small things will help you to stay in Kotlin. And yes Kotlin will definitely be easy and fun once you get used to it. So lets see Kotlin RecyclerView Example.

Kotlin RecyclerView example video

  • You can also go through this video explanation.

Kotlin RecyclerView Example

Create a new project

  • So first create a new Android Studio project using Kotlin.
  • Once the project is loaded, it comes in. activity_main.xml And delete hello world text view.

Add RecyclerView

  • Now find RecyclerView and drag it to you activity_main.xml (See image for help).

Kotlin RecyclerView Example

  • When you drag RecyclerView it will ask you to add the RecyclerView dependency.

Kotlin RecyclerView Example

  • So the xml code for us activity_main.xml Will happen.
<?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="net.simplifiedcoding.recyclerviewexample.MainActivity">


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />
    
</android.support.constraint.ConstraintLayout>

Creating a list layout using CardView

  • Now we will create a new layout for the list item. So create a new layout resource file and name it list_layout.xml.
  • Now look again for the same search and just drag it to the layout you created. It will again ask you to add a CardView dependency.

Kotlin RecyclerView Example

  • Now use the following xml code for the layout. Here I am going to display only the name and address. But you can design anything for your list.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textViewUsername"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Belal Khan"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

            <TextView
                android:id="@+id/textViewAddress"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Ranchi, Jharkhand"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

  • Now this list is for layout. The above xml code will generate the following layout.
Kotlin RecyclerView Example
Kotlin RecyclerView Example
  • Now lets create data class for list model.

Model making

  • The list is about the user so we will create a user class.
  • Create a new Kotlin file and write the following code.
package net.simplifiedcoding.recyclerviewexample

/**
 * Created by Belal on 6/19/2017.
 */

data class User(val name: String, val address: String)

  • Now lets create an adapter.

Creating RecyclerView Adapter

  • If you have already created a RecyclerView in Java, you may already know that we need an adapter to display data in RecyclerView.
  • So create a new Kotlin class by name CustomAdapter.kt And write the following code.
package net.simplifiedcoding.recyclerviewexample

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView

/**
 * Created by Belal on 6/19/2017.
 */

class CustomAdapter(val userList: ArrayList<User>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    //this method is returning the view for each item in the list
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)
        return ViewHolder(v)
    }

    //this method is binding the data on the list
    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(userList[position])
    }

    //this method is giving the size of the list
    override fun getItemCount(): Int {
        return userList.size
    }

    //the class is hodling the list view
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(user: User) {
            val textViewName = itemView.findViewById(R.id.textViewUsername) as TextView
            val textViewAddress  = itemView.findViewById(R.id.textViewAddress) as TextView
            textViewName.text = user.name
            textViewAddress.text = user.address
        }
    }
}

  • Now the last step is creating RecyclerView itself.

Creating RecyclerView

  • Come now MainActivity.kt And write the following code.
package net.simplifiedcoding.recyclerviewexample

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.LinearLayout

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //getting recyclerview from xml
        val recyclerView = findViewById(R.id.recyclerView) as RecyclerView
        
        //adding a layoutmanager
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)


        //crating an arraylist to store users using the data class user
        val users = ArrayList<User>()

        //adding some dummy data to the list
        users.add(User("Belal Khan", "Ranchi Jharkhand"))
        users.add(User("Ramiz Khan", "Ranchi Jharkhand"))
        users.add(User("Faiz Khan", "Ranchi Jharkhand"))
        users.add(User("Yashar Khan", "Ranchi Jharkhand"))

        //creating our adapter
        val adapter = CustomAdapter(users)

        //now adding the adapter to recyclerview
        recyclerView.adapter = adapter
    }
}

  • Now it is for coding. Try running the application.
Kotlin RecyclerView Example
Kotlin RecyclerView Example
  • As you can see it is working perfectly.

So for this we have to Kotlin RecyclerView Example friend. If you have any confusion and questions, then let us discuss the comments section. And I will keep posting more tutorials using Android development with Kotlin. And on your behalf I want you to share this post if you think it is useful. Thank you 4


Source link

About dmtechnolab

Check Also

Simplified Coding

Android ViewModel Unit Test Tutorial – Android Coding by DMTechnolab

Hi guys welcome Android ViewModel Unit Test Tutorial. This post is also part of our …

One comment

  1. I’m gone to say to my little brother, that he should also go to see this weblog on regular basis
    to get updated from newest reports.

Leave a Reply

Your email address will not be published. Required fields are marked *