检测项目外部的RecyclerView单击 [英] Detect click on RecyclerView outside of items

查看:80
本文介绍了检测项目外部的RecyclerView单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RecyclerView,其中有2个项目无法填满整个屏幕.如何检测到用户单击了RecyclerView的空白部分(意味着直接单击了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)?

推荐答案

您可以为RecyclerView子类化并重写dispatchTouchEvent()方法来完成此任务.使用findChildViewUnder()方法,我们可以确定触摸事件是否在子视图之外发生,并使用interface通知监听器是否发生.在下面的示例中,OnNoChildClickListener interface提供了该功能.

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);
    }
}

注意:这是针对RecyclerView的,它来自我在此处关于GridView的答案.

NB: This is adapted for RecyclerView from my answer here concerning GridView.

这篇关于检测项目外部的RecyclerView单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆