The problem: I haven't found a solution that works and allows me to use onLongClickListener
in my recyclerview adapter
I understand that my options seem to be either implementing an interface or using a lambda, however I've been trying everything I can find and none of them are working.
places I have tried solutions from:
Item Onclick RecyclerView Kotlin Android
RecyclerView onClick in kotlin
How to add a click listener to my recycler view (Android kotlin)
RecyclerView itemClickListener in Kotlin
Recyclerview Card Item Onclick Kotlin
and everything else I could find when googling "kotlin recyclerview onClickAdapter"
I get different errors with every solution, but the main takeaway is that none of them are working, which tells me that there is probably a problem with my adapter code to begin with.
Example of one error I get: If I try to use setOnClickListener
in the bind
function of TaskViewHolder
, I get the error of
Wrong return type, expecting Boolean, received Unit
There is no passed in list because I use submitList from a viewmodel with a room database
The adapter code is based off of the Room with a View code
I have
Adapter Code:
class TaskRvAdapter : ListAdapter<Task, TaskRvAdapter.TaskViewHolder>(TaskComparator()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
return TaskViewHolder.create(parent)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val current = getItem(position)
holder.bind(current.task)
}
class TaskViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val taskItemView: TextView = itemView.findViewById(R.id.task_rv_item)
fun bind(text: String?) {
taskItemView.text = text
}
companion object {
fun create(parent: ViewGroup): TaskViewHolder {
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.task_rv_item, parent, false)
return TaskViewHolder(view)
}
}
}
class TaskComparator : DiffUtil.ItemCallback<Task>() {
override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean {
return oldItem.task == newItem.task
}
}
}
try with this code, properly formatted
fun bind(text: String?) {
taskItemView.text = text
itemView.setOnClickListener {
Log.i("TaskRvAdapter", "item clicked: "+text)
}
itemView.setOnLongClickListener{
Log.i("TaskRvAdapter", "item long clicked: "+text)
return@setOnLongClickListener true
}
}