I was exploring RecyclerView
and I was surprised to see that RecyclerView
does not have onItemClickListener()
. Because RecyclerView
extends
android.view.ViewGroup
and ListView
extends
android.widget.AbsListView
. However I solved my problem by writing onClick
in my RecyclerView.Adapter
:
public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
}
@Override
public void onClick(View v) {
}
}
But still I want to know why Google removed onItemClickListener()
?
Is there a performance issue or something else?
As far as I understand MLProgrammer-CiM answer, simply it's possible to just do this:
After reading @MLProgrammer-CiM's answer, here is my code:
I have done this way, its very simple:
Just add 1 Line for Clicked RecyclerView position:
Full code for ViewHolder class:
Hope this will help you.
Inside View Holder
Inside OnBindViewHolder()
And let me know, do you have any question about this solution ?
Instead of implementing interface View.OnClickListener inside view holder or creating and interface and implementing interface in your activity.. I used this code for simple on OnClickListener implementation.
An alternative solution is the one proposed by Hugo Visser, an Android GDE. He made a licence-free class available for you to just drop in your code and use it.
Usage:
(it also support long item click)
Implementation (comments added by me):
also create a file
values/ids.xml
and put this in it:This class works by attaching a
RecyclerView.OnChildAttachStateChangeListener
to theRecyclerView
. This listener is notified every time a child is attached or detached from theRecyclerView
. The code use this to append a tap/long click listener to the view. That listener ask theRecyclerView
for theRecyclerView.ViewHolder
which contains the position.You could also adapt the code to give you back the holder itself if you need more.
Keep in mind that it's COMPLETELY fine to handle it in your adapter by setting on each view of your list a click listener, like other answer proposed. It's just not the most efficient thing to do (you create a new listener every time you reuse a view) but it works and in most cases it's not an issue.
About the Why
RecyclerView
does not have anonItemClickListener
.The
RecyclerView
is a toolbox, in contrast of the oldListView
it has less build in features and more flexibility. TheonItemClickListener
is not the only feature being removed from ListView. But it has lot of listeners and method to extend it to your liking, it's far more powerful in the right hands ;).In my opinion the most complex feature removed in
RecyclerView
is the Fast Scroll. Most of the other features can be easily re-implemented.