RecyclerView items unclickable
from the CommonsWare Community archivesAt October 1, 2020, 7:42pm, vedy asked:
Hi Mark,
I have a very simple recyclerView as shown below in the code,
The issue is that it does not respond to clicks (in this case it should just display a smiple snackbar), I’ve made sure that my cardView is set to clickable in the xml file.
I’ve also moved the code to the onBindViewHolder , but still no response to clicks.
I’m testing on API 29 Emulator.
I’ve looked at other examples and the only difference that I can see is that the some of the examples add an Interface , then implementing the interface in the activity or another class. but as far as the code below I’m not sure why it’s not working. no action in logcat either.
So I would like to ask:
- How can I make the items respond to clicks?
- How do you usually handle the clicks in a production app? Do you prefer using the Interface method?
Thanks again
class RecyclerAdapter(private var items: List<Result>) :
RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val TAG: String = "View Holder"
val itemTitle: TextView = itemView.findViewById(R.id.tv_item_title)
val itemDetail: TextView = itemView.findViewById(R.id.tv_item_description)
val itemPicture: ImageView = itemView.findViewById(R.id.iv_image)
init {
itemView.setOnClickListener { v: View ->
val position: Int = adapterPosition
Snackbar.make(v, "You clicked on ${items[position].strEvent}", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
Log.d(TAG, ": clicked ${items[position].strEvent}")
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.recycler_item, parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemTitle.text = items[position].strEvent
holder.itemDetail.text = items[position].strDescriptionEN
Glide.with(holder.itemPicture.context).load(items[position].strThumb)
.into(holder.itemPicture)
}
}
At October 1, 2020, 8:03pm, mmurphy replied:
Off the cuff, what you have should work. Here are some examples from Elements of Android Jetpack that demonstrate clicks on RecyclerView
rows:
- https://gitlab.com/commonsguy/cw-jetpack-kotlin/-/tree/v1.1/RecyclerViewBasics
- https://gitlab.com/commonsguy/cw-jetpack-kotlin/-/tree/v1.1/FragmentManual
- https://gitlab.com/commonsguy/cw-jetpack-kotlin/-/tree/v1.1/InLivingColor
You might want to compare and contrast your implementation with mine and see where they differ.
I would pass a function type into the ViewHolder
that can be invoked on a click event.