Adapter callback in Android using lambda function of Kotlin

Adapter callback in Android using lambda function of Kotlin:

Kotlin provides a lots of different options for concise code writing. Lambda function or lambdas are similar to Java lambdas. In this post, I will show you one common use case of lambda function.

Adapter and interface :

We need one adapter class for a recycler view. It uses one ViewHolder to load data to the recycler view cells. Adapter is a different class and we need to use it in the Activity we are using for the recycler view.

User interaction part is written inside the ViewHolder of the Adapter. For example, if the user clicks on a button, onClickListener is written inside the ViewHolder.

In Java, to pass the data from the ViewHolder to the activity on any user action, one interface is used. If I write the same pattern in Kotlin :

  1. Create one interface:
interface ItemClickListener{
			fun onClick(id: Int)
}
  1. Pass that interface to the Adapter and use it in onClick of the button or any other view:
class MyAdapter(val itemClickListener: ItemClickListener){
	....

	inner class MyViewHolder: RecyclerView.ViewHolder{
		....
		....
		button.setOnClickListener{itemClickListener.onClick(id)}
	}
}
  1. Implement this Interface in the activity and override the onClick method :
class MyActivity: AppCompatActivity(), ItemClickListener{

	....
	var myAdapter = MyAdapter(this)
	....
	
	override fun onClick(id: Int){
		...
		...
	}

}

The MyAdapter object is created in the activity MyActivity. On item click, it will call the onClick method in this activity.

Adapter and lambda:

The above process is a three step way. We can remove the part of creating a interface class by using lambdas :

  1. Pass one lambda function to the adapter instead of an interface and call that lambda to send back the id:
class MyAdapter(val itemClickListener: (id)-> Unit){
	....

	inner class MyViewHolder: RecyclerView.ViewHolder{
		....
		....
		button.setOnClickListener{itemClickListener(id)}
	}
}
  1. In the activity, inject the lambda:
class MyActivity: AppCompatActivity(), ItemClickListener{

	....
	var myAdapter = MyAdapter{id -> onClick(id)}
	....
	
	fun onClick(id: Int){
		...
		...
	}

}

That’s all, plain and simple.

Using lambda, it becomes easier to handle user interaction. But interface is more easier for different types of click handlings. For example, if you have more than one type of click handling, then using an interface will make the process smooth. You can define all at one place instead of having different lambdas to pass to the constructor.

You might also like: