Home > Software engineering >  Kotlin how pass parameter to funcion onClick in Adapter to ViewHolder?
Kotlin how pass parameter to funcion onClick in Adapter to ViewHolder?

Time:04-16

I have an Adapter:

    class TripsAdapter(
    onClickButtonAction: (TripId : Int) -> Unit,
): ListAdapter<Trip, TripssViewHolder>(TripsDiffCallBack()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TripssViewHolder {
        return TripsViewHolder(
            ItemsTripsBinding.inflate(
                LayoutInflater.from(parent.context), parent, false), parent.context)
    }

    override fun onBindViewHolder(holder: TripsViewHolder, position: Int) {
        holder.bind(getItem(position), onClickButtonAction ) <-- here I don't know how pass this function to ViewHolder
    }
}

And here is bind function in ViewHolder:

    fun bind(trip: Trip, onClickButtonAction : (Trip: Int) -> Unit) <- here is wrong code I think{

// And here I want to reaact on button click and pass ID to fragment like this: 

binding.button.setOnClickListener{
    onClickButtonAction.invoke()
}

}

And I want to receive it in Fragment like this:

 TripsAdapter = TripsAdapter(onClickButtonAction = { id ->

        do magic :P 

    })

Is it posible to pass this ID like funciton? I dont want to use interface. I want to pass Id on click from ViewHolder to Fragment.

CodePudding user response:

You can pass a method as lambda as a callback . And since its a callback it should be Global so you do not have to pass it to ViewHolder further. Also u need to declare the lambda as val so that u can access it in the class.

I have created an example below .

class TripAdapter(val onClickButtonAction: (trip : Trip, view:View?) -> Unit) : ListAdapter<Trip, TripAdapter.TripsViewHolder>(TripsDiffCallBack) {
inner class TripsViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    fun bind(trip: Trip) {
        binding.button.setOnClickListener {
            onClickButtonAction(trip, it)
        }
    }
}
}

this is how your lambda will look i have changed the parameters just in case . passing whole object of Trip and also passing the clicked View this can be helpful for handling clicks on multiple views.

Now wherever u are using this Adapter you create its as below :-

val adapter = TripAdapter(::onTripClickListener)


private fun onTripClickListener(trip:Trip, view: View?){

}
  • Related