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)
}
}
}
}
CodePudding user response:
Your code for the Adapter is alright, it seems. Firstly, whenever you have a lambda parameter, it must be set to the last of the list.
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)
}
}
And make sure your ProductResultData
implements Parcelable
interface.