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!
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.
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 ...
These required methods are as follows: onCreateViewHolder(ViewGroup parent, int viewType) onBindViewHolder(RecyclerView. ViewHolder holder, int position)
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.
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
}
});
}
See Jacob's implementation of RecyclerView.OnItemTouchListener
. I think it's the best solution.
Hope it will help you. Regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With