Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView - Where should I handle its click events?

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!

like image 530
Hadi Satrio Avatar asked Dec 24 '14 06:12

Hadi Satrio


People also ask

Where do you add the android onClick attribute to make items in a RecyclerView respond to clicks?

Where do you add the android:onClick attribute to make items in a RecyclerView respond to clicks? In the layout file that displays the RecyclerView, add it to the element. Add it to the layout file for an item in the row.

Which interface do you need to implement in order to listen and respond to user clicks in a RecyclerView?

In a nutshell, The Activity class will implement an interface for onClick event, this interface will be passed to the RecyclerView Adapter class, then the ViewHolder class in the RecyclerView will call onClick method defined in the interface, which will pass the view and position of the clicked item to the onClick ...

What are the three mandatory methods of a RecyclerView?

These required methods are as follows: onCreateViewHolder(ViewGroup parent, int viewType) onBindViewHolder(RecyclerView. ViewHolder holder, int position)

In what situation should one use RecyclerView over ListView?

Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.


2 Answers

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
        }
    });
}
like image 116
Rat-a-tat-a-tat Ratatouille Avatar answered Sep 22 '22 21:09

Rat-a-tat-a-tat Ratatouille


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

Hope it will help you. Regards.

like image 43
Volodymyr Yatsykiv Avatar answered Sep 20 '22 21:09

Volodymyr Yatsykiv