I have been creating a Gallery
derivative that uses a limited number of View
s and, as such, the Adapter
needs to be able to populate these View
s ahead of time during a scroll or a fling. To do this, I need to get the direction of motion from the onFling(...)
and onScroll(...)
events.
How can I use the distanceX
parameter in onScroll(...)
and the velocityX
parameter in onFling(...)
to determine which way the Gallery
is travelling, and therefore which View
to prepare next?
The signs of the velocity parameters in onFling(...)
and the distance parameters on onScroll(...)
are opposite. In order to correctly determine which direction a Gallery
is moving, the code should be as follows:
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
//if distanceX is POSITIVE, the Views are travelling left
//therefore the selection position is INCREASING
return super.onScroll(e1, e2, distanceX*mVelocityFactor, distanceY*mVelocityFactor);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//if velocityX is NEGATIVE, the Views are travelling left
//therefore the selection position is DECREASING
return super.onFling(e1, e1, velocityX*mVelocityFactor, velocityY*mVelocityFactor);
}
By the way, mVelocityFactor
is just a constant I introduced to make the scroll/fling a little less energetic. I found 0.6 to be quite a nice value—it still feels intuitive to scroll but the flings are less violent.