Kotlin RecyclerView Adapter 多个回调函数

Thi*_*ice 1 android kotlin android-recyclerview

如何将多个回调函数返回到 RecyclerView 的 Activity/Fragment?

我对 RecyclerView 中的每个项目都有多个选项(编辑、删除、CheckedAsComplete、视图),并且我希望在 RecyclerView 的 Activity/Fragment 中为每个项目提供回调函数。

以下是我如何在适配器中获得回调的链接:https://www.geeksforgeeks.org/kotlin-lambda-functions-for-recyclerview-adapter-callbacks-in-android/

我只需要知道适配器中是否可以有多个回调,如果可以,我该如何实现它?

我的活动的适配器代码:

val adapter = ProductAdapter(this) {
    deleteProduct(it),
    editProduct(it),
    viewProduct(it),
    checkAsComplete(it)
}
Run Code Online (Sandbox Code Playgroud)

这是我的适配器的构造函数:

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
}
Run Code Online (Sandbox Code Playgroud)

我对 kotlin 还很陌生,所以我非常感谢您的帮助!

Sta*_*dar 5

您可以使用不同的方法。这并不取决于您有多少事件。例如,对于enum类,您可以使用具有多个选项的单个回调

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

    enum class ClickEvent {
      DELETE,
      EDIT,
      VIEW,
      COMPLETE
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

val adapter = ProductAdapter{ event, item ->
    when(event){
      DELETE -> deleteProduct(item)
      ....//All other enum values
    }
}
Run Code Online (Sandbox Code Playgroud)