Pass value from recycler view adapter to activity – Android Kotlin

In this tutorial, we will teach you how you can pass value from the recycler view adapter to activity in Kotlin. First, you need to create an interface:

// file name = RVInterface.kt

package com.adnantech.myapp

import android.view.View

interface RVInterface {
    fun onClick(view: View)
}

Here, “RVInterface” is short for “Recycler View Interface”. Now, suppose we have the following model class:

// file name = User.kt

package com.adnantech.myapp

class User(val name: String) {
    //
}

And we create an array list of 3 users.

val users: ArrayList<User> = ArrayList()
users.add(User("Adnan"))
users.add(User("Tech"))
users.add(User("Developer"))

Then you need to create an instance of your interface in your activity class:

private val rvInterfaceInstance: RVInterface = object : RVInterface {
    override fun onClick(view: View) {
        val index: Int = recyclerView.getChildAdapterPosition(view)
        if (users.size > index) {
            Log.i("mylog", users[index].name)
        }
    }
}

This will override the “onClick” function created in the interface. When this function is called, it will get the item’s index in the recycler view. Check the index must not be outbound in the “users” array. Then display the user name in logcat.

After that, you need to pass this interface instance to your adapter:

val adapter: UsersAdapter = UsersAdapter(users, rvInterfaceInstance)

Since we are sending the interface instance as a parameter, so we can easily get it in our adapter’s constructor:

class UsersAdapter(
    private var users: ArrayList<User>,
    private var rvInterfaceInstance: RVInterface
)

And finally in your adapter, inside the “onBindViewHolder” method, we can call the following function to call the interface method inside the activity class:

holder.itemView.setOnClickListener {
    rvInterfaceInstance.onClick(holder.itemView)
}

This will call the interface method when the item in the adapter is clicked. But you can add it to any button click listener as well.

6 Replies to “Pass value from recycler view adapter to activity – Android Kotlin”

  1. Thanks for your personal marvelous posting! I certainly enjoyed reading it, you happen to be a great author.I will be sure to bookmark your blog and definitely will come back in the future. I want to encourage continue your great work, have a nice holiday weekend!

  2. I am regular visitor, how are you everybody? This article posted at this web page is really pleasant.

  3. wonderful points altogether, you simply received a logo new reader. What might you recommend about your put up that you simply made some days in the past? Any positive?

  4. It’s really very complicated in this full of activity life to listen news on TV, therefore I simply use world wide web for that purpose, and take the newest news.

Comments are closed.