3

I have this code which implements a RecyclerView and I want to add to it some gestures. I want 2 things to do and I don't know because I'm new to this.

  1. When someone clicks on RecyclerView I want to catch the event from the Activity before goes down to recycler. That's why I return true from dispatchTouchEvent. But it does not work because onTouch is called.

  2. In case we allow the event to pass down, when the touch event goes to recycler (OnTouch Method), Activity's onTouchEvent is not called. It is supposed to be called because the event handling bubbles up.

    public class MainActivity extends AppCompatActivity implements View.OnTouchListener{
    
    private RecyclerView recyclerView;
    private GestureDetectorCompat detector;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)  {
    
        super.onCreate(savedInstanceState);
    
        detector = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener() {
    
            @Override
            public boolean onFling (MotionEvent e1, MotionEvent e2,float velocityX,
            float velocityY){
                return false;
            }
    
        });
    
        recyclerView.setOnTouchListener(this);
    
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return detector.onTouchEvent(event);
    }
    
    @Override
    public boolean onTouch(View v,MotionEvent event) {
        return detector.onTouchEvent(event);
    }
    
    @Override
        public boolean dispatchTouchEvent(MotionEvent ev){
        super.dispatchTouchEvent(ev);
        return true;
    }
    }
    
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
Nick
  • 2,818
  • 5
  • 42
  • 60

1 Answers1

0

You don't want recycler view to eat event's then you have two way's

That's why I return true from dispatchTouchEvent

  1. Return false from dispatchTouchEvent, when you do this in recyclerView then dispatchTouchEvent() of recyclerView's child is not called so event will not even go down so no bubble up will happen. That means onTouch/onTouchEvent of recyclerView or any child of it will also not be called.Directly onTouch on Activity will be called.

  2. Return false from onTouch() in this case the event's will go down till all the child view and if they are not consumed then will reach recycler View and is you return false from here then Activity's onTouch will be called.

NOTE: So you have to choose one you can't have both.

Anmol
  • 8,110
  • 9
  • 38
  • 63