1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.launcher3.util; 18 19 import android.content.Context; 20 import android.view.MotionEvent; 21 import android.view.VelocityTracker; 22 import android.view.View; 23 import android.view.ViewConfiguration; 24 25 public class VerticalFlingDetector implements View.OnTouchListener { 26 27 private static final float CUSTOM_SLOP_MULTIPLIER = 2.2f; 28 private static final int SEC_IN_MILLIS = 1000; 29 30 private VelocityTracker mVelocityTracker; 31 private float mMinimumFlingVelocity; 32 private float mMaximumFlingVelocity; 33 private float mDownX, mDownY; 34 private boolean mShouldCheckFling; 35 private double mCustomTouchSlop; 36 37 public VerticalFlingDetector(Context context) { 38 ViewConfiguration vc = ViewConfiguration.get(context); 39 mMinimumFlingVelocity = vc.getScaledMinimumFlingVelocity(); 40 mMaximumFlingVelocity = vc.getScaledMaximumFlingVelocity(); 41 mCustomTouchSlop = CUSTOM_SLOP_MULTIPLIER * vc.getScaledTouchSlop(); 42 } 43 44 @Override 45 public boolean onTouch(View v, MotionEvent ev) { 46 if (mVelocityTracker == null) { 47 mVelocityTracker = VelocityTracker.obtain(); 48 } 49 mVelocityTracker.addMovement(ev); 50 switch (ev.getAction()) { 51 case MotionEvent.ACTION_DOWN: 52 mDownX = ev.getX(); 53 mDownY = ev.getY(); 54 mShouldCheckFling = false; 55 break; 56 case MotionEvent.ACTION_MOVE: 57 if (mShouldCheckFling) { 58 break; 59 } 60 if (Math.abs(ev.getY() - mDownY) > mCustomTouchSlop && 61 Math.abs(ev.getY() - mDownY) > Math.abs(ev.getX() - mDownX)) { 62 mShouldCheckFling = true; 63 } 64 break; 65 case MotionEvent.ACTION_UP: 66 if (mShouldCheckFling) { 67 mVelocityTracker.computeCurrentVelocity(SEC_IN_MILLIS, mMaximumFlingVelocity); 68 // only when fling is detected in down direction 69 if (mVelocityTracker.getYVelocity() > mMinimumFlingVelocity) { 70 cleanUp(); 71 return true; 72 } 73 } 74 // fall through. 75 case MotionEvent.ACTION_CANCEL: 76 cleanUp(); 77 } 78 return false; 79 } 80 81 private void cleanUp() { 82 if (mVelocityTracker == null) { 83 return; 84 } 85 mVelocityTracker.recycle(); 86 mVelocityTracker = null; 87 } 88 } 89