Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin RecyclerView Adapter multiple callback functions

How do I have multiple callback function back to the Activity/Fragment of a RecyclerView?

I have multiple options for each item in the RecyclerView (Edit, Delete, CheckedAsComplete, View) and I would like to have callback function for each of them in the Activity/Fragment of the RecyclerView.

Here is a link of how I got one callback in the Adapter: https://www.geeksforgeeks.org/kotlin-lambda-functions-for-recyclerview-adapter-callbacks-in-android/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I just need to know if it is possible to have multiple callbacks in the adapter and if so, how do I implement it?

My Activity’s Adapter Code:

val adapter = ProductAdapter(this) {
    deleteProduct(it),
    editProduct(it),
    viewProduct(it),
    checkAsComplete(it)
}

Here is my Adapter’s Constructor:

class ProductAdapter(
    private var context: Context,
    private val deleteProduct: (ItemTable) -> Unit,
    private val editProduct: (ItemTable) -> Unit,
    private val viewProduct: (ItemTable) -> Unit,
    private val checkedAsComplete: (ItemTable) -> Unit
): RecyclerView.Adapter<ProductAdapter.ItemProductViewHolder>() {
    // Rest of RecyclerView Adapter Code
}

I’m pretty new to kotlin so I would really appreciate your help!

>Solution :

You can use curly braces out only for the last callback of the list.

Assuming you declared the following methods in your activity :

  • fun deleteProduct(itemTable: ItemTable)
  • fun editProduct(itemTable: ItemTable)
  • fun checkAsComplete(itemTable: ItemTable)
  • fun viewProduct(itemTable: ItemTable)

You can use named parameters and you have two choices

With method reference

val adapter = ProductAdapter(
    context = this,
    deleteProduct = ::deleteProduct,
    editProduct  = ::editProduct,
    viewProduct = ::viewProduct,
    checkAsComplete = ::checkAsComplete
)

With lambda

val adapter = ProductAdapter(
    context = this,
    deleteProduct = { deleteProduct(it) },
    editProduct  = { editProduct(it) },
    viewProduct = { viewProduct(it) },
    checkAsComplete = { checkAsComplete(it) }
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading