Reputation: 577
Please check the sample code and comments below,
class MainActivity : AppCompatActivity(), MyListener {
fun OnViewItemClicked(){
// do something
}
}
class AnotherClass() : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// how do i set this to OnViewItemClicked declared in class MainActivity?
holder.itemView.setOnClickListener(OnViewItemClicked);
}
}
Upvotes: 0
Views: 167
Reputation: 11477
Just pass the Listener instance
to the adapter:- like :-
val adapter = AnotherClass(this@MainActivity)
Then in adapter
class AnotherClass(private val listener: MainActivity): RecyclerView.Adapter<MyAdapter.ViewHolder>() {
....
....
holder.itemView.setOnClickListener {
listener.OnViewItemClicked()
}
....
}
Explanation -
This is done with the help of kotlin lambda
, i.e, equivalent to :-
val clickLambda: (View) -> Unit = {
listener.OnViewItemClicked()
}
Edit :- Instead of doing this you can directly pass in a lambda of type (View) -> Unit
from the activity !
Upvotes: 3