Clicklistener Not Working In Recyclerview
Im following this link answer--> https://stackoverflow.com/a/32323801/12553303 ...on click of item im getting an error of invalid product id...but how do i get id from adapter
Solution 1:
To get response/data back from adapter to activity, you'll need to implement callback pattern like below example:
RecyclerView Adapter sudo code:
classRecyclerViewAdapter(
other variables,
privateval dataCallback: (Desired data type you want to return to activity) -> Unit// This is how you can construct lambda callback in Kotlin
): RecyclerView.Adaper..(){
overridefunonBindViewHolder(...) {
// Let's say here you have click listener or some other event on which you want data to send back to activity then simply call like below:
dataCallback(outputData) // This can be `dataList?.get(position)?.product?.id`
}
}
Activity callback sudo code:
classSampleActivity: AppCompatActivity() {
lateinitvar adapter: RecyclerViewAdapter
overridefunonCreate(...){
adapter = RecyclerViewAdapter(other values) { desiredData ->
// Here you can receive data back as callback
}
// Example from O.P.// val adapter = CartAdapter(this@AddToCart, dataList) { output -> }
}
}
Basically you create a callback receiver type on your adapter constructor as following:
nameOfCallbackVariable: (TypeOfDataYouWantToProvideBack) -> ReturnType
I.e. productSelectedCallback: (Int) -> Unit
where you send your selected id (Int
) back to consumer.
When you need to provide that data back, you can invoke it like this: nameOfCallbackVariable(valueOfIntType)
.
Post a Comment for "Clicklistener Not Working In Recyclerview"