I'm trying to pass the clicked element to the calling activity in my RecyclerView in the onBindViewHolder method. There I need the just clicked element or the number. How do I do it?
class AddNewHomeFragment : Fragment() {
rv_img.layoutManager = GridLayoutManager(requireContext(),3)
adapter = CustomerAdapter(requireContext(),listImg){
//NEED CLICKED ITEM NUMBER HERE
var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent,IMAGE_REQUEST)
}
... }
Adapter Class (CustomerAdapter):
class CustomerAdapter(val context: Context,
private val listImg:ArrayList<Bitmap>, private val onClickFunction: ((Any?) -> Unit)? = null):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>() {
...
override fun onBindViewHolder(holder: MyCustomViewHolder, position: Int) {
holder.customImg.setImageBitmap(listImg[position])
holder.customImg.setOnClickListener {
[email protected]?.invoke(listImg[position])
}
}
}
CodePudding user response:
Your constructor should be:
class CustomerAdapter(val context: Context,
private val listImg:ArrayList<Bitmap>,
private val onClickFunction: ((Int) -> Unit)? = null
):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>()
Your function takes an integer position, not an Any, and it can't be null.
Your usage of it should go
adapter = CustomerAdapter(requireContext(),listImg){ position->
var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent,IMAGE_REQUEST)
}
Then you can use position within the function.