5

I want to implement onScroll, when scroll event occurs. However I don't understand how can I detect the scroll from bottom up with the parameters that I receive with onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY).

I would be happy to get some guidelines how to implement it or some examples.

Vera
  • 171
  • 2
  • 12

1 Answers1

3

You should be able to use the distanceY parameter to determine whether the view was scrolled up or down. distanceY represents the distance along the Y axis that has been scrolled since the last call to onScroll(). If the value of distanceY is greater than zero, the view has been scrolled from a lower position on the Y axis to a higher position on the Y axis.

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
    if (distanceY > 0) {
        // Scrolled upward
        if (e2.getAction() = MotionEvent.ACTION_UP) {
            // The pointer has gone up, ending the gesture
        }
    }
    return false;
}

Note: I have not tested if the MotionEvent.ACTION_UP will solve your need to check when scrolling has ended, but it seems practical in theory. Also note that technically the gesture could also end if the MotionEvent's action is set to MotionEvent.ACTION_CANCEL.

Ryan
  • 3,414
  • 2
  • 27
  • 34
  • Thanks for your answer. Do I need to consider the motion events? What do they contribute? – Vera May 05 '16 at 07:13
  • 1
    The `MotionEvent`s contain much more fine grain data on the movement being executed such as touch state. `e1` is the first down motion event that started the scrolling (this usually stays constant during the scroll) while `e2` is the move motion event that triggered the current `onScroll`. You can call `getY` on both motion events to calculate the change in Y, but `distanceY` should be able to more simply provide you the same solution. – Ryan May 05 '16 at 13:23
  • Great, I understand. Thank you ! – Vera May 05 '16 at 13:35
  • How can I detect that the scroll is ended? Because the method called multiple times during the scroll. – Vera May 05 '16 at 17:56
  • I have not tested this, but one way to know if scrolling has ended is by checking if `e2`'s current action is `MotionEvent.ACTION_UP`. This assumes that scrolling ends when the touch that initiated the scroll is released. I.e. the pointer is no longer touching the screen. I'll update my answer to give you a code example of what that might look like. – Ryan May 05 '16 at 18:08
  • That would be great! Thanks. – Vera May 06 '16 at 07:37
  • Tried to do as you said, unfortunately it is not working. – Vera May 10 '16 at 17:42
  • 2
    Doubt it will be useful to you, but most likely to future readers; `onScroll` is called while scrolling, `onFling` is called once the finger is lifted. – Irhala Nov 14 '17 at 15:25
  • in onScroll, e2 never has MotionEvent.ACTION_UP action. it ends with ACTION_MOVE – Derek Zhu Apr 14 '19 at 23:43