Reputation: 2564
I'm trying to use setOnClickListener and setOnLongClickListener in adapter to pass the click to the activity. I've searched a lot of and I only found some examples of how to do one clicklistener but not handle both at the same time.
How can I handle both listeners in the activity?
ADAPTER
class BrowserAdapter(private val voucherList: List<String>?, private val listener: (String) -> Unit) : RecyclerView.Adapter<BrowserAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(inflate(parent.context, R.layout.item_web, parent, false))
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(voucherList!![position], listener)
}
override fun getItemCount(): Int {
return voucherList!!.size
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(urlData: String, listener: (String) -> Unit) = with(itemView) {
tx_url.text = urlData
itemView.setOnClickListener{
listener(urlData)
}
itemView.setOnLongClickListener{
listener(urlData)
true
}
}
}
}
ACTIVITY
rv_web_items.adapter = BrowserAdapter(Preferences.getFavouritesWebsites()) {
presenter.onItemClick(it)
}
Upvotes: 0
Views: 1040
Reputation: 11477
The lambda function of the activity should look like :-
val listener : (String, Boolean) -> Unit = { urlData, isLongClick -> presenter.onItemClick(urlData) }
Then pass the lambda ( listener
) to the adapter
rv_web_items.adapter = BrowserAdapter(Preferences.getFavouritesWebsites(), listener)
Upvotes: 2
Reputation: 2157
I will suggest you to add listeners at onBindViewHolder
like this:
holder.itemView.setOnClickListener {
}
and also long click:
holder.itemView.setOnLongClickListener { true }
and what about sending data to activity. First step - create interface:
interface Click {
fun sendData(..., position: Int, ...) // it is only example
}
the the second step use it at your adapter:
open class Adapter(..., ..., private val click: Click)
then handle click and send data:
holder.itemView.setOnClickListener {
click.sendData(your_data)
}
then in activity you have to declare this interface:
val adapter = Adapter(..., ..., this@YourActivity)
function for getting data in your activity:
override fun sendData(your_data) {
}
and also don't forget to implement this interface:
class JobsList : ..., ..., Click
I hope it will help you. Good Luck :)
Upvotes: 1