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.