How to implement click listener for RecyclerView Items
RecyclerView
is a great class that you should consider over ListView for
building list interfaces. It offers more flexibility and has built-in hooks
that make implementing animations and custom layouts much easier compared to
ListView
RecyclerViews allow us to handle item taps in a slightly different way.
Instead of providing a listener on the RecyclerView itself, the
responsibility is handed off to whoever wants to implement the interface
for a click listener.
Learn about How to implement RecyclerView using RecyclerView.Adapter
Let's see how to implement
OnItemClickListener
in RecyclerView
.1. Implement View.OnClickListener
in ViewHolder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @Override public void onClick(View v) { } }
2. Create an interface named OnItemClickListener
public interface OnItemClickListener { void onItemClick(FeedItem item); }
3. Add OnItemClickListener
to your adapter
private OnItemClickListener onItemClickListener; public void setOnItemClickListener(OnItemClickListener onItemClickListener){ this.onItemClickListener = onItemClickListener; }
4. Pass the item to the onClick
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @Override public void onClick(View v) { onItemClickListener.onItemClick(feedItem); } }
5. add setOnItemClickListener
from the adapter into your class file
In the activity class, let set the click listener to adapter by calling the setOnItemClickListener() method.
adapter.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(FeedItem item) { Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_LONG).show(); } });