11

Prior to the introduction of RecyclerView (and its mandatory ViewHolder pattern), I usually delegate any click events to its corresponding Activity/Fragment using setOnItemClickListener(). (Because I mainly see Activity/Fragment as a "controller" object when developing for Android, thus any modification to the view should be done in it.)

Now, as RecyclerView doesn't really treat its children the same way and that setOnItemClickListener() (or similar) methods are no longer implemented for it - where should I handle click events that may take place? I don't know.. but handling them in an Adapter seems awkward to me.

How are we supposed to do it?

Thanks in advance!

Hadi Satrio
  • 4,272
  • 2
  • 24
  • 45

2 Answers2

5

Create your own viewHolder for the recycler view as we always do it, and in the onBindView method, set the click listener to the view you wish to perform the click.

@Override
public void onBindViewHolder(final ViewHolder viewHolder, int position) {
viewHolder.mRelContent.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // perform ur click here
        }
    });
}
  • I ended up using your method. Volodymyr's answer is great for lists that do not need to handle long press events, otherwise one would need to do some serious tweaking to make it work. Yours is much more easier to implement. Thanks! – Hadi Satrio Dec 25 '14 at 06:47
  • This is a simple solution however if you would like to reuse this ViewHolder elsewhere in your code and provide different click/touch handlers, then this approach is not suitable. You will need to handle the events outside the adapter (or ViewHolder). –  Sep 28 '15 at 12:26
  • I thinks best way to handle this is inside activity or fragment – Azlan Jamal Mar 21 '16 at 17:21
4

See Jacob's implementation of RecyclerView.OnItemTouchListener. I think it's the best solution.

Hope it will help you. Regards.

Community
  • 1
  • 1
Volodymyr Yatsykiv
  • 3,181
  • 1
  • 24
  • 28
  • why do you think this method is better than the one OP accepted as answer? – veritas Feb 19 '16 at 04:28
  • 1
    @veritas because in accepted answer you have to set click listener every time when you bind view holder, in this case you set touch listener for RecyclerView in one place and that's it. Like on ListView. – Volodymyr Yatsykiv Feb 19 '16 at 10:03