I'm trying to implement an item click event
of a recyclerview
.
In Java
, the typical method of creating an interface
in an adapter
for clicking an item, implementing it in an activity
, and passing an anonymous object
to the adapter
was used.
However, Kotlin
accepts lambda expressions
and can pass them as arguments
.
So I don't necessarily need to use an interface
, am I?
Or is there some good reason to use interfaces
as much as possible?
You can use high-order functions to accomplish that without using interfaces.
Here is an example:
Fragment/Activity
recycler_view_photos.adapter = PhotosAdapter {
actionAfterClickOnItem()
}
private fun actionAfterClickOnItem() {
//stuff
}
Adapter
class PhotosAdapter(val onItemClicked: () -> Unit) {
//stuff
inner class PhotoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(photo: Photo) {
//stuff
itemView.setOnClickListener {
onItemClicked.invoke()
}
}
}
}
Interfaces are good to create contracts between components, give a type to a class, and create events, but with Kotlin as you mentioned, you can use lambdas and do the same thing with fewer lines of code.
Interfaces are best for click listeners in recyclerView like you have views in each view are three buttons like delete, remove and add button so just make three methods in interface
fun onDeleteClick(position,Item) //Here item of that model which is passed in adapter
fun onAddClick(position,Item)
fun onRemoveClick(position,Item)
implement this interface with your activity and pass it in your adapter and then in your adapter create click listener like this
Holder.itemBinding.delete.setOnClickListener{ clickListener.OnDeleteClick(position, Item) }
So instead of passing lambda function for each button just use interface for all clicks and override in your activity
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.