I have a RecyclerView with 2 items that don\'t fill the whole screen. How can I detect that the user clicked on the empty part of the RecyclerView (meaning clicked directly on t
You can subclass RecyclerView
and override the dispatchTouchEvent()
method to accomplish this. Using the findChildViewUnder()
method, we can determine if a touch event occurs outside of the child Views, and use an interface
to notify a listener if it is. In the following example, the OnNoChildClickListener
interface
provides that functionality.
public class TouchyRecyclerView extends RecyclerView
{
// Depending on how you're creating this View,
// you might need to specify additional constructors.
public TouchyRecyclerView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
private OnNoChildClickListener listener;
public interface OnNoChildClickListener
{
public void onNoChildClick();
}
public void setOnNoChildClickListener(OnNoChildClickListener listener)
{
this.listener = listener;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
// The findChildViewUnder() method returns null if the touch event
// occurs outside of a child View.
// Change the MotionEvent action as needed. Here we use ACTION_DOWN
// as a simple, naive indication of a click.
if (event.getAction() == MotionEvent.ACTION_DOWN
&& findChildViewUnder(event.getX(), event.getY()) == null)
{
if (listener != null)
{
listener.onNoChildClick();
}
}
return super.dispatchTouchEvent(event);
}
}
NB: This is adapted for RecyclerView
from my answer here concerning GridView
.