Home > Software engineering >  Kotlin RecyclerView Adapter multiple callback functions
Kotlin RecyclerView Adapter multiple callback functions

Time:06-04

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/

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!

CodePudding user response:

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) }
)

CodePudding user response:

You can use different approach. This does not depend on how many events you have. For example with enum class you can use single callback with many options

class ProductAdapter(private val clickEvent: (ClickEvent, ItemTable) -> Unit): 
    RecyclerView.Adapter<ProductAdapter.ItemProductViewHolder>() {

    enum class ClickEvent {
      DELETE,
      EDIT,
      VIEW,
      COMPLETE
    }
}

Usage:

val adapter = ProductAdapter{ event, item ->
    when(event){
      DELETE -> deleteProduct(item)
      ....//All other enum values
    }
}
  • Related