I'm trying to implement a draggable button that should also be flingable.
Unfortunately the system stops sending MotionEvents after the drag is started. Therefore the GestureDetector.OnGestureListener.onFling() method is never called.
Is there a way to intercept those events before they are consumed by the drag system?
I also tried to create my own FlingDetector, but it's not reliable across different devices and screen densities:
public class FlingDetector {
private final int MIN_FLING_SPEED = 3;
private OnFlingListener mOnFlingListener;
private float mCurrentX = 0;
private float mCurrentY = 0;
private long mLastMovementTime = 0;
private double mCurrentVelocity = 0;
private final float mDensity;
public FlingDetector(OnFlingListener onFlingListener, Context context) {
mOnFlingListener = onFlingListener;
mDensity = context.getResources().getDisplayMetrics().density;
}
public void onMovementStart(float x, float y) {
mCurrentX = x;
mCurrentY = y;
mLastMovementTime = System.currentTimeMillis();
mCurrentVelocity = 0;
}
public void onMovementEnd(float x, float y) {
long currentTime = System.currentTimeMillis();
float distanceX = Math.abs(mCurrentX - x) / mDensity;
float distanceY = Math.abs(mCurrentY - y) / mDensity;
float distance = (float) Math.sqrt(Math.pow(distanceX, 2) +
Math.pow(distanceY, 2));
mCurrentVelocity = (distance / (currentTime - mLastMovementTime));
if(mCurrentVelocity > MIN_FLING_SPEED) {
mOnFlingListener.onFling((int) (mCurrentVelocity + 0.5));
} else {
Log.d("test", "Distance: " + distance);
Log.d("test", "Time Delta: " + (currentTime - mLastMovementTime));
Log.d("test", "Speed: " + mCurrentVelocity);
}
}
public interface OnFlingListener {
void onFling(int speed);
}
}
GestureDetectorCompat
here. Hope it helps. – Mannose