Oma*_*mar 13 android android-recyclerview
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 the RecyclerView and not one of its items)?
Ang*_*ski 14
如评论中所述
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
if (motionEvent.getAction() != MotionEvent.ACTION_UP) {
return false;
}
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null) {
// tapped on child
return false;
} else {
// Tap occured outside all child-views.
// do something
return true;
}
}
@Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
});
Run Code Online (Sandbox Code Playgroud)
Mik*_* M. 11
您可以子类化RecyclerView并覆盖该dispatchTouchEvent()方法来完成此任务.使用该findChildViewUnder()方法,我们可以确定触摸事件是否发生在子视图之外,并使用an interface来通知侦听器是否存在.在以下示例中,OnNoChildClickListener interface提供了该功能.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
注:这适用于RecyclerView从我的答案在这里有关GridView.