Detect click on RecyclerView outside of items

前端 未结 6 2419
醉话见心
醉话见心 2021-02-18 22:10

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

6条回答
  •  孤街浪徒
    2021-02-18 23:03

    @driss-bounouar's answer is almost right although this will prevent the user from scrolling the recycler view as any down event will cause your action to happen. With a slight modification where we record the down event and then check on the up event if the coordinates have not changed much, then fire the event.

    private MotionEvent lastRecyclerViewDownTouchEvent;
    myRecyclerView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            if (event.getAction() == MotionEvent.ACTION_DOWN && myRecyclerView.findChildViewUnder(event.getX(), event.getY()) == null) {
                                lastRecyclerViewDownTouchEvent = event;
                            } else if (event.getAction() == MotionEvent.ACTION_UP && myRecyclerView.findChildViewUnder(event.getX(), event.getY()) == null
                                    && lastRecyclerViewDownTouchEvent != null) {
                                // Check to see if it was a tap or a swipe
                                float xDelta = Math.abs(lastRecyclerViewDownTouchEvent.getX() - event.getX());
                                float yDelta = Math.abs(lastRecyclerViewDownTouchEvent.getY() - event.getY());
                                if (xDelta < 30 && yDelta < 30) {
                                    // Do action
                                }
                                lastRecyclerViewDownTouchEvent = null;
                            }
                            return false;
                        }
                    });
    

提交回复
热议问题