如何通过捆绑包将数据从适配器传递到 kotlin 中的片段?

how to pass data from adapter to fragments in kotlin via bundle?

I've been trying to pass data(the email and phone of a user) from my adapter to my fragment. From what I've read online I should use a interface for this but I cant I want to use bundle . Can anyone explain in steps how I should pass data via bundle and how to recieve it in fragment. Below is my adapter.

class ProductAdapter(
    private val onItemClick: (item: ProductResultData) -> Unit,
    private val items: List<ProductResultData>
): RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {

    lateinit var context: Context

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {

        context = parent.context

        val binding: ProductItemDataBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.rv_product _item,
            parent,
            false)

        return ProductViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        val productItem = items[position]
        holder.bindItem(productItem,context)
    }

    override fun getItemCount(): Int {
        return items.size
    }

    inner class ProductViewHolder(private val binding: ProductItemDataBinding): RecyclerView.ViewHolder(binding.root){


        @SuppressLint("SetTextI18n")
        fun bindItem(item: ProductResultData, context: Context){

            
            Glide.with(context)
                .load(R.drawable.img_kitchen)
                .placeholder(R.drawable.garden_kit)
                .into(binding.ivGardenKit)

            binding.tvProductName.text = item.product_name
           binding.tvPrice.text = "₹" +" "+item.price.toString() + "/ Kit"
            binding.tvProductDetails.text = item.about_product
           binding.cvProducts.setOnClickListener {

               onItemClick.invoke(item)
        }


        }
    }

}

你的适配器代码看起来没问题。首先,无论何时你有一个 lambda 参数,它都必须设置为列表的最后一个。

class ProductAdapter(
  private val items: List<ProductResultData
  private val onItemClick: (ProductResultData) -> Unit
)

// In your activity/fragment
binding.recyclerView.adapter = ProductAdapter(list) { item ->
  Bundle().apply {
    putParcelable("PRODUCT_ITEM", item)
  }.also {
    val yourFrag = YourFragment()
    yourFrag.args = it
    replaceFragment(yourFrag)
  }
}

并确保您的 ProductResultData 实现了 Parcelable 接口。