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!

1
  • make your custom ViewHolder implement OnClickListener Commented Dec 24, 2014 at 7:58

2 Answers 2

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
        }
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

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!
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).
I thinks best way to handle this is inside activity or fragment
4

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

Hope it will help you. Regards.

2 Comments

why do you think this method is better than the one OP accepted as answer?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.