Has anyone using RecyclerView
found a way to set an onClickListener
to items in the RecyclerView
?
I thought of setting a listener to each of the layouts for each item but that seems a little too much hassle
I'm sure there is a way for the RecyclerView
to listen for the onClick
event but I can't quite figure it out.
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
This was so hard for me to have on item click listener in the activity and also to have click listener for single view of the item that will not trigger on item click listener. After playing around with Jacob Tabak's answer I respect his answer for on item click if no other touch actions inside item are presented.
I have a custom
OnClickListener
interface that have on item click event which holds the clicked item's view and the item position from the adapter. I present an instance of it in the constructor(or it can be with setter) and attach it to the view holder container click listener.I also have other click listener in the Adapter(Can be in the view holder) which will handle current View click from the container.
In the activity you need to initialize the adapter by passing instance of the
OnItemClickListener
And my ViewHolder
You can implement OnClickListener to your ViewHolder class
And onBindViewHolder set your view holder's item
For me the clean way to do that is this one.
Adapter constructor
`private class EnvironmentTypeRecyclerViewAdapter extends RecyclerView.Adapter {
The Linked Interface
As the API's have radically changed, It wouldn't surprise me if you were to create an
OnClickListener
for each item. It isn't that much of a hassle though. In your implementation ofRecyclerView.Adapter<MyViewHolder>
, you should have:The
onClick
method:Check out a similar question @CommonsWare's comment links to this, which implements the
OnClickListener
interface in theviewHolder
.Here's a simple example of the
ViewHolder
:The
Adapter
then looks like this:you can easily define setOnClickListener in your ViewHolder class as follow :