Android RecyclerView Click: How to Get ViewHolder Reference
Introduction
When working with the Android RecyclerView, it is common to want to handle click events on the individual items in the list. In order to do this, we need to be able to retrieve a reference to the ViewHolder associated with the clicked item. In this article, we will explore how to get the ViewHolder reference when handling RecyclerView click events.
Accessing the ViewHolder Reference
To get the ViewHolder reference, we need to implement the RecyclerView.OnItemTouchListener interface and override the onInterceptTouchEvent() method. This method is called when a touch event is intercepted before it is handled by the RecyclerView.
Within the onInterceptTouchEvent() method, we can use the findChildViewUnder() method to get the View that was touched. We can then use the getChildViewHolder() method to get the ViewHolder associated with that View.
Here is an example implementation:
public class RecyclerViewItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(ViewHolder viewHolder, int position);
}
public RecyclerViewItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && e.getAction() == MotionEvent.ACTION_UP) {
ViewHolder viewHolder = view.getChildViewHolder(childView);
mListener.onItemClick(viewHolder, viewHolder.getAdapterPosition());
return true;
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {}
}
In this example, we have created a custom RecyclerViewItemClickListener that takes an OnItemClickListener interface as a parameter. The OnItemClickListener interface has a single method, onItemClick(), that takes the ViewHolder reference and the position of the clicked item as parameters.
Within the onInterceptTouchEvent() method, we check if a childView was touched and if the listener is not null and the action is MotionEvent.ACTION_UP (meaning the touch event has ended). If these conditions are met, we retrieve the ViewHolder reference using getChildViewHolder() and call the onItemClick() method on the listener.
Conclusion
In order to handle click events on items in an Android RecyclerView, we need to be able to retrieve a reference to the ViewHolder associated with the clicked item. By implementing the RecyclerView.OnItemTouchListener interface and using the findChildViewUnder() and getChildViewHolder() methods, we can easily get the ViewHolder reference and perform any necessary actions.
Leave a Reply
Related posts