Example usage for android.view VelocityTracker obtain

List of usage examples for android.view VelocityTracker obtain

Introduction

In this page you can find the example usage for android.view VelocityTracker obtain.

Prototype

static public VelocityTracker obtain() 

Source Link

Document

Retrieve a new VelocityTracker object to watch the velocity of a motion.

Usage

From source file:com.glm.view.SlidingLayer.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHereX(ev, mInitialX)
            && !allowSlidingFromHereY(ev, mInitialY)) {
        return false;
    }//from  w  ww .ja va  2 s . c  om

    final int action = ev.getAction();

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
            || action == MotionEvent.ACTION_OUTSIDE) {
        mLastTouchAllowed = false;
    } else {
        mLastTouchAllowed = true;
    }

    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(ev);

    switch (action & MotionEventCompat.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        completeScroll();

        // Remember where the motion event started
        mLastX = mInitialX = ev.getX();
        mLastY = mInitialY = ev.getY();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    case MotionEvent.ACTION_MOVE:
        if (!mIsDragging) {
            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (pointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, pointerIndex);
            final float xDiff = Math.abs(x - mLastX);
            final float y = MotionEventCompat.getY(ev, pointerIndex);
            final float yDiff = Math.abs(y - mLastY);
            if (xDiff > mTouchSlop && xDiff > yDiff) {
                mIsDragging = true;
                mLastX = x;
                setDrawingCacheEnabled(true);
            } else if (yDiff > mTouchSlop && yDiff > xDiff) {
                mIsDragging = true;
                mLastY = y;
                setDrawingCacheEnabled(true);
            }
        }
        if (mIsDragging) {
            // Scroll to follow the motion event
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (activePointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            final float deltaX = mLastX - x;
            final float deltaY = mLastY - y;
            mLastX = x;
            mLastY = y;
            final float oldScrollX = getScrollX();
            final float oldScrollY = getScrollY();
            float scrollX = oldScrollX + deltaX;
            float scrollY = oldScrollY + deltaY;

            // Log.d("Layer", String.format("Layer scrollX[%f],scrollY[%f]", scrollX, scrollY));
            final float leftBound, rightBound;
            final float bottomBound, topBound;
            switch (mScreenSide) {
            case STICK_TO_LEFT:
                topBound = bottomBound = rightBound = 0;
                leftBound = getWidth(); // How far left we can scroll
                break;
            case STICK_TO_MIDDLE:
                topBound = getHeight();
                bottomBound = -getHeight();
                leftBound = getWidth();
                rightBound = -getWidth();
                break;
            case STICK_TO_RIGHT:
                rightBound = -getWidth();
                topBound = bottomBound = leftBound = 0;
                break;
            case STICK_TO_TOP:
                topBound = getHeight();
                bottomBound = rightBound = leftBound = 0;
                break;
            case STICK_TO_BOTTOM:
                topBound = rightBound = leftBound = 0;
                bottomBound = -getHeight();
                break;
            default:
                topBound = bottomBound = rightBound = leftBound = 0;
                break;
            }
            if (scrollX > leftBound) {
                scrollX = leftBound;
            } else if (scrollX < rightBound) {
                scrollX = rightBound;
            }
            if (scrollY > topBound) {
                scrollY = topBound;
            } else if (scrollY < bottomBound) {
                scrollY = bottomBound;
            }

            // Keep the precision
            mLastX += scrollX - (int) scrollX;
            mLastY += scrollY - (int) scrollY;
            scrollTo((int) scrollX, (int) scrollY);
        }
        break;
    case MotionEvent.ACTION_UP:
        if (mIsDragging) {
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            final int initialVelocityX = (int) VelocityTrackerCompat.getXVelocity(velocityTracker,
                    mActivePointerId);
            final int initialVelocityY = (int) VelocityTrackerCompat.getYVelocity(velocityTracker,
                    mActivePointerId);
            final int scrollX = getScrollX();
            final int scrollY = getScrollY();
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            final int totalDeltaX = (int) (x - mInitialX);
            final int totalDeltaY = (int) (y - mInitialY);

            boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, scrollY, initialVelocityX,
                    initialVelocityY, totalDeltaX, totalDeltaY);
            switchLayer(nextStateOpened, true, true, initialVelocityX, initialVelocityY);

            mActivePointerId = INVALID_POINTER;
            endDrag();
        } else if (mIsOpen && closeOnTapEnabled) {
            closeLayer(true);
        } else if (!mIsOpen && openOnTapEnabled) {
            openLayer(true);
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsDragging) {
            switchLayer(mIsOpen, true, true);
            mActivePointerId = INVALID_POINTER;
            endDrag();
        }
        break;
    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        mLastX = MotionEventCompat.getX(ev, index);
        mLastY = MotionEventCompat.getY(ev, index);
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        mLastX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        mLastY = MotionEventCompat.getY(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }
    if (mActivePointerId == INVALID_POINTER) {
        mLastTouchAllowed = false;
    }
    return true;
}

From source file:bk.vinhdo.taxiads.utils.view.SlidingLayer.java

@Override
public boolean onTouchEvent(MotionEvent ev) {

    final int action = ev.getAction();

    if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHereX(ev, mInitialX)
            && !allowSlidingFromHereY(ev, mInitialY)) {
        return false;
    }//from  w  w w  . ja  v a  2 s . c o m

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
            || action == MotionEvent.ACTION_OUTSIDE) {
        mLastTouchAllowed = false;
    } else {
        mLastTouchAllowed = true;
    }

    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(ev);

    switch (action & MotionEventCompat.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        completeScroll();

        // Remember where the motion event started
        mLastX = mInitialX = ev.getX();
        mLastY = mInitialY = ev.getY();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    case MotionEvent.ACTION_MOVE:
        if (!mIsDragging) {
            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (pointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, pointerIndex);
            final float xDiff = Math.abs(x - mLastX);
            final float y = MotionEventCompat.getY(ev, pointerIndex);
            final float yDiff = Math.abs(y - mLastY);
            if (xDiff > mTouchSlop && xDiff > yDiff) {
                mIsDragging = true;
                mLastX = x;
                setDrawingCacheEnabled(true);
            } else if (yDiff > mTouchSlop && yDiff > xDiff) {
                mIsDragging = true;
                mLastY = y;
                setDrawingCacheEnabled(true);
            }
        }
        if (mIsDragging) {
            // Scroll to follow the motion event
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (activePointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            if (mOnInteractListener != null) {
                mOnInteractListener.onActionMove(x, y);
            }
            final float deltaX = mLastX - x;
            final float deltaY = mLastY - y;
            mLastX = x;
            mLastY = y;
            final float oldScrollX = getScrollX();
            final float oldScrollY = getScrollY();
            float scrollX = oldScrollX + deltaX;
            float scrollY = oldScrollY + deltaY;

            // Log.d("Layer", String.format("Layer scrollX[%f],scrollY[%f]",
            // scrollX, scrollY));
            final float leftBound, rightBound;
            final float bottomBound, topBound;
            switch (mScreenSide) {
            case STICK_TO_LEFT:
                topBound = bottomBound = rightBound = 0;
                leftBound = getWidth(); // How far left we can scroll
                break;
            case STICK_TO_MIDDLE:
                topBound = getHeight();
                bottomBound = -getHeight();
                leftBound = getWidth();
                rightBound = -getWidth();
                break;
            case STICK_TO_RIGHT:
                rightBound = -getWidth();
                topBound = bottomBound = leftBound = 0;
                break;
            case STICK_TO_TOP:
                topBound = getHeight();
                bottomBound = rightBound = leftBound = 0;
                break;
            case STICK_TO_BOTTOM:
                topBound = rightBound = leftBound = 0;
                bottomBound = -getHeight();
                break;
            default:
                topBound = bottomBound = rightBound = leftBound = 0;
                break;
            }
            if (scrollX > leftBound) {
                scrollX = leftBound;
            } else if (scrollX < rightBound) {
                scrollX = rightBound;
            }
            if (scrollY > topBound) {
                scrollY = topBound;
            } else if (scrollY < bottomBound) {
                scrollY = bottomBound;
            }

            // TODO top/bottom bounds
            // Keep the precision
            mLastX += scrollX - (int) scrollX;
            mLastY += scrollY - (int) scrollY;
            scrollTo((int) scrollX, (int) scrollY);
        }
        break;
    case MotionEvent.ACTION_UP:

        if (mIsDragging) {

            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            final int initialVelocityX = (int) VelocityTrackerCompat.getXVelocity(velocityTracker,
                    mActivePointerId);
            final int initialVelocityY = (int) VelocityTrackerCompat.getYVelocity(velocityTracker,
                    mActivePointerId);
            final int scrollX = getScrollX();
            final int scrollY = getScrollY();
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            final int totalDeltaX = (int) (x - mInitialX);
            final int totalDeltaY = (int) (y - mInitialY);

            boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, scrollY, initialVelocityX,
                    initialVelocityY, totalDeltaX, totalDeltaY);

            boolean isControlled = false;
            if (isControlled) {
                break;
            }

            switchLayer(nextStateOpened, true, true, initialVelocityX, initialVelocityY);

            mActivePointerId = INVALID_POINTER;
            Log.d("", "end drag from action up");
            endDrag();
        } else if (mIsOpen && closeOnTapEnabled) {
            closeLayer(true);
        } else if (!mIsOpen && openOnTapEnabled) {
            openLayer(true);
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsDragging) {
            switchLayer(mIsOpen, true, true);
            mActivePointerId = INVALID_POINTER;
            Log.d(TAG, "end drag from action cancel");
            endDrag();
        }
        break;
    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        mLastX = MotionEventCompat.getX(ev, index);
        mLastY = MotionEventCompat.getY(ev, index);
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        mLastX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        mLastY = MotionEventCompat.getY(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }
    if (mActivePointerId == INVALID_POINTER) {
        mLastTouchAllowed = false;
    }
    return true;
}

From source file:com.example.lansosdk.util.SlidingLayer.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    if (!mEnabled) {
        return false;
    }/* ww  w  .j  a v a 2  s . co m*/

    final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;

    if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
        mIsDragging = false;
        mIsUnableToDrag = false;
        mActivePointerId = INVALID_POINTER;
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
        return false;
    }

    if (action != MotionEvent.ACTION_DOWN) {
        if (mIsDragging) {
            return true;
        } else if (mIsUnableToDrag) {
            return false;
        }
    }

    switch (action) {
    case MotionEvent.ACTION_MOVE:
        final int activePointerId = mActivePointerId;
        if (activePointerId == INVALID_POINTER) {
            break;
        }

        final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId);
        if (pointerIndex == -1) {
            mActivePointerId = INVALID_POINTER;
            break;
        }

        final float x = MotionEventCompat.getX(ev, pointerIndex);
        final float dx = x - mLastX;
        final float xDiff = Math.abs(dx);
        final float y = MotionEventCompat.getY(ev, pointerIndex);
        final float dy = y - mLastY;
        final float yDiff = Math.abs(y - mLastY);

        if (xDiff > mTouchSlop && xDiff > yDiff && allowDragingX(dx, mInitialX)) {
            // mIsDragging = true;
            mLastX = x;
            setDrawingCacheEnabled(true);
        } else if (yDiff > mTouchSlop && yDiff > xDiff && allowDragingY(dy, mInitialY)) {
            //  mIsDragging = true;
            mLastY = y;
            setDrawingCacheEnabled(true);
        }
        break;

    case MotionEvent.ACTION_DOWN:
        mActivePointerId = ev.getAction() & (Build.VERSION.SDK_INT >= 8 ? MotionEvent.ACTION_POINTER_INDEX_MASK
                : MotionEventCompat.ACTION_POINTER_INDEX_MASK);
        mLastX = mInitialX = MotionEventCompat.getX(ev, mActivePointerId);
        mLastY = mInitialY = MotionEventCompat.getY(ev, mActivePointerId);
        if (allowSlidingFromHereX(ev, mInitialX)) {
            mIsDragging = false;
            mIsUnableToDrag = false;
            // If nobody else got the focus we use it to close the layer
            return super.onInterceptTouchEvent(ev);
        } else if (allowSlidingFromHereY(ev, mInitialY)) {
            mIsDragging = false;
            mIsUnableToDrag = false;
            // If nobody else got the focus we use it to close the layer
            return super.onInterceptTouchEvent(ev);
        } else {
            mIsUnableToDrag = true;
        }
        break;
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        break;
    }

    if (!mIsDragging) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);
    }

    return mIsDragging;
}

From source file:com.antew.redditinpictures.library.widget.SwipeListView.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Store width of this list for usage of swipe distance detection
    if (mViewWidth < 2) {
        mViewWidth = getWidth();/*w w w. j  a v  a  2s  .  c  o m*/
    }

    switch (MotionEventCompat.getActionMasked(event)) {
    case MotionEvent.ACTION_DOWN:
        int[] viewCoords = new int[2];
        // Figure out where the touch occurred.
        getLocationOnScreen(viewCoords);

        int touchX = (int) event.getRawX() - viewCoords[0];
        int touchY = (int) event.getRawY() - viewCoords[1];

        Rect rect = new Rect();
        View child;

        int childCount = getChildCount();
        for (int i = getHeaderViewsCount(); i <= childCount; i++) {
            // Go through each child view (excluding headers) and see if our touch pressed it.
            child = getChildAt(i);

            if (child != null) {
                //Get the child hit rectangle.
                child.getHitRect(rect);
                //If the child would be hit by this press.
                if (rect.contains(touchX, touchY)) {
                    // DIRECT HIT! You sunk my battleship. Now that we know which view was touched, store it off for use if a move occurs.
                    View frontView = child.findViewById(mFrontViewId);
                    View backView = child.findViewById(mBackViewId);
                    // Create our view pair.
                    mViewPair = new SwipeableViewPair(frontView, backView);
                    break;
                }
            }
        }

        if (mViewPair != null) {
            // If we have a view pair, record details about the inital touch for use later.
            mDownX = event.getRawX();
            mVelocityTracker = VelocityTracker.obtain();
            mVelocityTracker.addMovement(event);
        }
        break;
    case MotionEvent.ACTION_UP:
        if (mVelocityTracker != null) {
            // Add the movement so we can calculate velocity.
            mVelocityTracker.addMovement(event);
            mVelocityTracker.computeCurrentVelocity(1000);

            float deltaX = event.getRawX() - mDownX;
            float velocityX = Math.abs(mVelocityTracker.getXVelocity());
            float velocityY = Math.abs(mVelocityTracker.getYVelocity());

            if (mViewPair != null) {
                boolean shouldSwipe = false;

                // If the view has been moved a significant enough distance or if the view was flung, check to see if we should swipe it.
                if ((Math.abs(deltaX) > mViewWidth / 2 && mState == State.SWIPING)
                        || (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
                                && velocityX > velocityY)) {
                    if (mSwipeDirection == SWIPE_DIRECTION_BOTH) {
                        // If the list is setup to swipe in either direction, just let it go.
                        shouldSwipe = true;
                    } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) {
                        // If the list is only setup to swipe left, then only allow swiping to the left.
                        shouldSwipe = true;
                    } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) {
                        // If the list is only setup to swipe right, then only allow swiping to the right.
                        shouldSwipe = true;
                    }
                }

                if (shouldSwipe) {
                    // If a swipe should occur meaning someone has let go of a view they were moving and it was far/fast enough for us to consider it a swipe start the animations.
                    mViewPair.mFrontView.animate().translationX(deltaX >= 0 ? mViewWidth : -mViewWidth).alpha(0)
                            .setDuration(mAnimationTime);
                    mViewPair.mBackView.animate().alpha(1).setDuration(mAnimationTime);
                    // Now that the item is open, store it off so we can close it when we scroll if needed.
                    mSwipedViews.put(mViewPair.hashCode(), mViewPair);
                    // Clear out current variables as they are no longer needed and recycle the velocity tracker.
                    resetState();
                } else {
                    // If the user let go of the view and we don't think the swipe was intended to occur (it was cancelled basically) reset the views.
                    // Make sure the back disappears, since if it has buttons these can intercept touches from the front view.
                    mViewPair.mBackView.setVisibility(View.GONE);
                    mViewPair.mFrontView.animate().translationX(0).alpha(1).setDuration(mAnimationTime);
                    // Clear out current variables as they are no longer needed and recycle the velocity tracker.
                    resetState();
                }
            }
        }
        break;
    case MotionEvent.ACTION_MOVE:
        if (mVelocityTracker != null && mState != State.SCROLLING) {
            // If this is an initial movement and we aren't already swiping.
            // Add the movement so we can calculate velocity.
            mVelocityTracker.addMovement(event);
            mVelocityTracker.computeCurrentVelocity(1000);

            float deltaX = event.getRawX() - mDownX;
            float velocityX = Math.abs(mVelocityTracker.getXVelocity());
            float velocityY = Math.abs(mVelocityTracker.getYVelocity());

            // If the movement has been more than what is considered slop, and they are clearing moving horizontal not vertical.
            if (Math.abs(deltaX) > mTouchSlop && velocityX > velocityY) {
                boolean initiateSwiping = false;

                if (mSwipeDirection == SWIPE_DIRECTION_BOTH) {
                    // If the list is setup to swipe in either direction, just let it go.
                    initiateSwiping = true;
                } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) {
                    // If the list is only setup to swipe left, then only allow swiping to the left.
                    initiateSwiping = true;
                } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) {
                    // If the list is only setup to swipe right, then only allow swiping to the right.
                    initiateSwiping = true;
                }

                if (initiateSwiping) {
                    ViewParent parent = getParent();
                    if (parent != null) {
                        // Don't allow parent to intercept touch (prevents NavigationDrawers from intercepting when near the bezel).
                        parent.requestDisallowInterceptTouchEvent(true);
                    }
                    // Change our state to swiping to start tranforming the item.
                    changeState(State.SWIPING);
                    // Make sure that touches aren't intercepted.
                    requestDisallowInterceptTouchEvent(true);

                    // Cancel ListView's touch to prevent it from being focused.
                    MotionEvent cancelEvent = MotionEvent.obtain(event);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL
                            | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    super.onTouchEvent(cancelEvent);
                } else {
                    // Otherwise we need to cancel the touch event to prevent accidentally selecting the item and also preventing the swipe in the wrong direction or an incomplete touch from moving the view.
                    MotionEvent cancelEvent = MotionEvent.obtain(event);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL
                            | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    super.onTouchEvent(cancelEvent);
                }
            }

            if (mState == State.SWIPING && mViewPair != null) {
                // Make sure the back is visible.
                mViewPair.mBackView.setVisibility(View.VISIBLE);
                //Fade the back in and front out as they move.
                mViewPair.mBackView.setAlpha(Math.min(1f, 2f * Math.abs(deltaX) / mViewWidth));
                mViewPair.mFrontView.setTranslationX(deltaX);
                mViewPair.mFrontView
                        .setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth)));
                return true;
            }
        }
        break;
    }
    return super.onTouchEvent(event);
}

From source file:com.klinker.android.sliding.MultiShrinkScroller.java

/**
 * Catch the touch event and act on it./*from   w w w  .  jav  a  2  s.  c o m*/
 * @param event the touch event.
 * @return true if we should start dragging, otherwise false.
 */
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    if (velocityTracker == null) {
        velocityTracker = VelocityTracker.obtain();
    }
    velocityTracker.addMovement(event);

    // The only time we want to intercept touch events is when we are being dragged.
    return shouldStartDrag(event);
}

From source file:com.example.lansosdk.util.SlidingLayer.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (!mEnabled || !mIsDragging && !mLastTouchAllowed && !allowSlidingFromHereX(ev, mInitialX)
            && !allowSlidingFromHereY(ev, mInitialY)) {
        return false;
    }/*from  w  ww. java 2s. co  m*/

    final int action = ev.getAction();

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL
            || action == MotionEvent.ACTION_OUTSIDE) {
        mLastTouchAllowed = false;
    } else {
        mLastTouchAllowed = true;
    }

    if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(ev);

    switch (action & MotionEventCompat.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        completeScroll();

        // Remember where the motion event started
        mLastX = mInitialX = ev.getX();
        mLastY = mInitialY = ev.getY();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    case MotionEvent.ACTION_MOVE:
        if (!mIsDragging) {
            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            if (pointerIndex == -1) {
                mActivePointerId = INVALID_POINTER;
                break;
            }
            final float x = MotionEventCompat.getX(ev, pointerIndex);
            final float xDiff = Math.abs(x - mLastX);
            final float y = MotionEventCompat.getY(ev, pointerIndex);
            final float yDiff = Math.abs(y - mLastY);
            //                if (xDiff > mTouchSlop && xDiff > yDiff) {
            //                    mIsDragging = true;
            //                    mLastX = x;
            //                    setDrawingCacheEnabled(true);
            //                } else if (yDiff > mTouchSlop && yDiff > xDiff) {
            //                    mIsDragging = true;
            //                    mLastY = y;
            //                    setDrawingCacheEnabled(true);
            //                }
        }

        //            if (mIsDragging) {  ??
        //                // Scroll to follow the motion event
        //                final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
        //                if (activePointerIndex == -1) {
        //                    mActivePointerId = INVALID_POINTER;
        //                    break;
        //                }
        //                final float x = MotionEventCompat.getX(ev, activePointerIndex);
        //                final float y = MotionEventCompat.getY(ev, activePointerIndex);
        //                final float deltaX = mLastX - x;
        //                final float deltaY = mLastY - y;
        //                mLastX = x;
        //                mLastY = y;
        //                final float oldScrollX = getScrollX();
        //                final float oldScrollY = getScrollY();
        //                float scrollX = oldScrollX + deltaX;
        //                float scrollY = oldScrollY + deltaY;
        //
        //                // Log.d("Layer", String.format("Layer scrollX[%f],scrollY[%f]", scrollX, scrollY));
        //                final float leftBound, rightBound;
        //                final float bottomBound, topBound;
        //                switch (mScreenSide) {
        //                case STICK_TO_LEFT:
        //                    topBound = bottomBound = rightBound = 0;
        //                    leftBound = getWidth(); // How far left we can scroll
        //                    break;
        //                case STICK_TO_MIDDLE:
        //                    topBound = getHeight();
        //                    bottomBound = -getHeight();
        //                    leftBound = getWidth();
        //                    rightBound = -getWidth();
        //                    break;
        //                case STICK_TO_RIGHT:
        //                    rightBound = -getWidth();
        //                    topBound = bottomBound = leftBound = 0;
        //                    break;
        //                case STICK_TO_TOP:
        //                    topBound = getHeight();
        //                    bottomBound = rightBound = leftBound = 0;
        //                    break;
        //                case STICK_TO_BOTTOM:
        //                    topBound = rightBound = leftBound = 0;
        //                    bottomBound = -getHeight();
        //                    break;
        //                default:
        //                    topBound = bottomBound = rightBound = leftBound = 0;
        //                    break;
        //                }
        //                if (scrollX > leftBound) {
        //                    scrollX = leftBound;
        //                } else if (scrollX < rightBound) {
        //                    scrollX = rightBound;
        //                }
        //                if (scrollY > topBound) {
        //                    scrollY = topBound;
        //                } else if (scrollY < bottomBound) {
        //                    scrollY = bottomBound;
        //                }
        //
        //                // Keep the precision
        //                mLastX += scrollX - (int) scrollX;
        //                mLastY += scrollY - (int) scrollY;
        //                scrollTo((int) scrollX, (int) scrollY);
        //            }
        break;
    case MotionEvent.ACTION_UP:
        if (mIsDragging) {
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            final int initialVelocityX = (int) VelocityTrackerCompat.getXVelocity(velocityTracker,
                    mActivePointerId);
            final int initialVelocityY = (int) VelocityTrackerCompat.getYVelocity(velocityTracker,
                    mActivePointerId);
            final int scrollX = getScrollX();
            final int scrollY = getScrollY();
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float y = MotionEventCompat.getY(ev, activePointerIndex);
            final int totalDeltaX = (int) (x - mInitialX);
            final int totalDeltaY = (int) (y - mInitialY);

            boolean nextStateOpened = determineNextStateOpened(mIsOpen, scrollX, scrollY, initialVelocityX,
                    initialVelocityY, totalDeltaX, totalDeltaY);
            switchLayer(nextStateOpened, true, true, initialVelocityX, initialVelocityY);

            mActivePointerId = INVALID_POINTER;
            endDrag();
        } else if (mIsOpen && closeOnTapEnabled) {
            closeLayer(true);
        } else if (!mIsOpen && openOnTapEnabled) {
            openLayer(true);
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsDragging) {
            switchLayer(mIsOpen, true, true);
            mActivePointerId = INVALID_POINTER;
            endDrag();
        }
        break;
    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        mLastX = MotionEventCompat.getX(ev, index);
        mLastY = MotionEventCompat.getY(ev, index);
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        mLastX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        mLastY = MotionEventCompat.getY(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }
    if (mActivePointerId == INVALID_POINTER) {
        mLastTouchAllowed = false;
    }
    return true;
}

From source file:com.cmad.swipe.SwipeRefreshLayout.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    ensureTarget();/*from  ww w .  j  a v a 2  s .co m*/

    final int action = MotionEventCompat.getActionMasked(ev);

    if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
        mReturningToStart = false;
    }

    if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
        // Fail fast if we're not in a state where a swipe is possible
        return false;
    }

    switch (action) {
    case MotionEvent.ACTION_DOWN:
        mLastMotionY = mInitialMotionY = ev.getY();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        mIsBeingDragged = false;
        speedLimited = false;
        alreadyTestSpeed = false;
        mCurrPercentage = 0;
        mIsPulling = false;
        mCanRefreshing = false;
        if (vTracker == null) {
            vTracker = VelocityTracker.obtain();
        } else {
            vTracker.clear();
        }
        vTracker.addMovement(ev);
        break;

    case MotionEvent.ACTION_MOVE:

        if (mActivePointerId == INVALID_POINTER) {
            Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
            return false;
        }

        final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
        if (pointerIndex < 0) {
            Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
            return false;
        }
        if (!alreadyTestSpeed) {
            vTracker.addMovement(ev);
            vTracker.computeCurrentVelocity(1000);
            if (vTracker.getYVelocity() > 120) {
                speedLimited = true;
                return false;
            }
            alreadyTestSpeed = true;
        } else {
            if (speedLimited)
                return false;
        }

        final float y = MotionEventCompat.getY(ev, pointerIndex);
        final float yDiff = y - mInitialMotionY;
        if (yDiff > mTouchSlop) {
            mLastMotionY = y;
            mIsBeingDragged = true;

        }
        break;

    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        break;

    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
        mIsBeingDragged = false;
        mCurrPercentage = 0;
        mActivePointerId = INVALID_POINTER;
        break;
    }

    return mIsBeingDragged;
}

From source file:com.achep.acdisplay.ui.fragments.AcDisplayFragment.java

@Override
public void onForwardedEvent(MotionEvent event, int activePointerId) {
    int action = event.getActionMasked();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        // Track the velocity of movement, so we
        // can do swipe-to-dismiss.
        mVelocityTracker = VelocityTracker.obtain();
        mTouchSticky = false;// w ww . ja  va 2 s  .  c o  m
    case MotionEvent.ACTION_MOVE:
    case MotionEvent.ACTION_UP:
        populateStdMotion(event);

        if (action != MotionEvent.ACTION_UP) {
            return; // Don't fall down.
        }

        boolean dismissing = swipeToDismiss();
        if (!dismissing) {
            if (mTouchSticky) {
                // Disable the default timeout mechanism and let
                // the selected widget to stay for a while.
                onWidgetStick(mSelectedWidget);
            } else if (mPressedIconView == null || !isPinnable()) {
                showHomeWidget();
            } else {
                onWidgetPin(mSelectedWidget);
            }
        }
    case MotionEvent.ACTION_CANCEL:
        mTouchHandler.removeCallbacksAndMessages(null);
        mVelocityTracker.recycle();
        mVelocityTracker = null;
        mTouchSticky = false;

        if (action == MotionEvent.ACTION_CANCEL) {
            showHomeWidget();
        }
        break;
    }
}

From source file:com.davidtpate.swipelistview.SwipeListView.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Store width of this list for usage of swipe distance detection
    if (mViewWidth < 2) {
        mViewWidth = getWidth();/*from  www. j a v a 2 s  .co m*/
    }

    switch (MotionEventCompat.getActionMasked(event)) {
    case MotionEvent.ACTION_DOWN:
        int[] viewCoords = new int[2];
        // Figure out where the touch occurred.
        getLocationOnScreen(viewCoords);

        int touchX = (int) event.getRawX() - viewCoords[0];
        int touchY = (int) event.getRawY() - viewCoords[1];

        Rect rect = new Rect();
        View child;

        int childCount = getChildCount();
        for (int i = getHeaderViewsCount(); i <= childCount; i++) {
            // Go through each child view (excluding headers) and see if our touch pressed it.
            child = getChildAt(i);

            if (child != null) {
                //Get the child hit rectangle.
                child.getHitRect(rect);
                //If the child would be hit by this press.
                if (rect.contains(touchX, touchY)) {
                    // DIRECT HIT! You sunk my battleship. Now that we know which view was touched, store it off for use if a move occurs.
                    View frontView = child.findViewById(mFrontViewId);
                    View backView = child.findViewById(mBackViewId);
                    // Create our view pair.
                    mViewPair = new SwipeableViewPair(frontView, backView);
                    break;
                }
            }
        }

        if (mViewPair != null) {
            // If we have a view pair, record details about the inital touch for use later.
            mDownX = event.getRawX();
            mVelocityTracker = VelocityTracker.obtain();
            mVelocityTracker.addMovement(event);
        }
        break;
    case MotionEvent.ACTION_UP:
        if (mVelocityTracker != null) {
            // Add the movement so we can calculate velocity.
            mVelocityTracker.addMovement(event);
            mVelocityTracker.computeCurrentVelocity(1000);

            float deltaX = event.getRawX() - mDownX;
            float velocityX = Math.abs(mVelocityTracker.getXVelocity());
            float velocityY = Math.abs(mVelocityTracker.getYVelocity());

            if (mViewPair != null) {
                boolean shouldSwipe = false;

                // If the view has been moved a significant enough distance or if the view was flung, check to see if we should swipe it.
                if ((Math.abs(deltaX) > mViewWidth / 2 && mState == State.SWIPING)
                        || (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity
                                && velocityX > velocityY)) {
                    if (mSwipeDirection == SWIPE_DIRECTION_BOTH) {
                        // If the list is setup to swipe in either direction, just let it go.
                        shouldSwipe = true;
                    } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) {
                        // If the list is only setup to swipe left, then only allow swiping to the left.
                        shouldSwipe = true;
                    } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) {
                        // If the list is only setup to swipe right, then only allow swiping to the right.
                        shouldSwipe = true;
                    }
                }

                if (shouldSwipe) {
                    // If a swipe should occur meaning someone has let go of a view they were moving and it was far/fast enough for us to consider it a swipe start the animations.
                    ViewPropertyAnimator.animate(mViewPair.mFrontView)
                            .translationX(deltaX >= 0 ? mViewWidth : -mViewWidth).alpha(0)
                            .setDuration(mAnimationTime);
                    ViewPropertyAnimator.animate(mViewPair.mBackView).alpha(1).setDuration(mAnimationTime);
                    // Now that the item is open, store it off so we can close it when we scroll if needed.
                    mSwipedViews.put(mViewPair.hashCode(), mViewPair);
                    // Clear out current variables as they are no longer needed and recycle the velocity tracker.
                    resetState();
                } else {
                    // If the user let go of the view and we don't think the swipe was intended to occur (it was cancelled basically) reset the views.
                    // Make sure the back disappears, since if it has buttons these can intercept touches from the front view.
                    mViewPair.mBackView.setVisibility(View.GONE);
                    ViewPropertyAnimator.animate(mViewPair.mFrontView).translationX(0).alpha(1)
                            .setDuration(mAnimationTime);
                    // Clear out current variables as they are no longer needed and recycle the velocity tracker.
                    resetState();
                }
            }
        }
        break;
    case MotionEvent.ACTION_MOVE:
        if (mVelocityTracker != null && mState != State.SCROLLING) {
            // If this is an initial movement and we aren't already swiping.
            // Add the movement so we can calculate velocity.
            mVelocityTracker.addMovement(event);
            mVelocityTracker.computeCurrentVelocity(1000);

            float deltaX = event.getRawX() - mDownX;
            float velocityX = Math.abs(mVelocityTracker.getXVelocity());
            float velocityY = Math.abs(mVelocityTracker.getYVelocity());

            // If the movement has been more than what is considered slop, and they are clearing moving horizontal not vertical.
            if (Math.abs(deltaX) > mTouchSlop && velocityX > velocityY) {
                boolean initiateSwiping = false;

                if (mSwipeDirection == SWIPE_DIRECTION_BOTH) {
                    // If the list is setup to swipe in either direction, just let it go.
                    initiateSwiping = true;
                } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) {
                    // If the list is only setup to swipe left, then only allow swiping to the left.
                    initiateSwiping = true;
                } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) {
                    // If the list is only setup to swipe right, then only allow swiping to the right.
                    initiateSwiping = true;
                }

                if (initiateSwiping) {
                    ViewParent parent = getParent();
                    if (parent != null) {
                        // Don't allow parent to intercept touch (prevents NavigationDrawers from intercepting when near the bezel).
                        parent.requestDisallowInterceptTouchEvent(true);
                    }
                    // Change our state to swiping to start tranforming the item.
                    changeState(State.SWIPING);
                    // Make sure that touches aren't intercepted.
                    requestDisallowInterceptTouchEvent(true);

                    // Cancel ListView's touch to prevent it from being focused.
                    MotionEvent cancelEvent = MotionEvent.obtain(event);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL
                            | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    super.onTouchEvent(cancelEvent);
                } else {
                    // Otherwise we need to cancel the touch event to prevent accidentally selecting the item and also preventing the swipe in the wrong direction or an incomplete touch from moving the view.
                    MotionEvent cancelEvent = MotionEvent.obtain(event);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL
                            | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    super.onTouchEvent(cancelEvent);
                }
            }

            if (mState == State.SWIPING && mViewPair != null) {
                // Make sure the back is visible.
                mViewPair.mBackView.setVisibility(View.VISIBLE);
                //Fade the back in and front out as they move.
                ViewHelper.setAlpha(mViewPair.mBackView, Math.min(1f, 2f * Math.abs(deltaX) / mViewWidth));
                ViewHelper.setTranslationX(mViewPair.mFrontView, deltaX);
                ViewHelper.setAlpha(mViewPair.mFrontView,
                        Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth)));
                return true;
            }
        }
        break;
    }
    return super.onTouchEvent(event);
}

From source file:com.albedinsky.android.ui.widget.ViewPagerWidget.java

/**
 * Ensures that the {@link #mVelocityTracker} is initialized.
 *//*from ww  w.j  a  va  2  s . co  m*/
private void ensureVelocityTracker() {
    if (mVelocityTracker == null)
        this.mVelocityTracker = VelocityTracker.obtain();
}