Example usage for android.view MotionEvent getX

List of usage examples for android.view MotionEvent getX

Introduction

In this page you can find the example usage for android.view MotionEvent getX.

Prototype

public final float getX() 

Source Link

Document

#getX(int) for the first pointer index (may be an arbitrary pointer identifier).

Usage

From source file:com.app.afteryou.ui.staggered.StaggeredGridView.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (!isEnabled()) {
        // A disabled view that is clickable still consumes the touch
        // events, it just doesn't respond to them.
        return isClickable() || isLongClickable();
    }// ww  w  .  j a v  a 2s . c o  m
    mVelocityTracker.addMovement(ev);
    final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;

    int motionPosition = pointToPosition((int) ev.getX(), (int) ev.getY());

    switch (action) {
    case MotionEvent.ACTION_DOWN:
        mVelocityTracker.clear();
        mScroller.abortAnimation();
        mLastTouchY = ev.getY();
        mLastTouchX = ev.getX();
        motionPosition = pointToPosition((int) mLastTouchX, (int) mLastTouchY);
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        mTouchRemainderY = 0;

        if (mTouchMode != TOUCH_MODE_FLINGING && !mDataChanged && motionPosition >= 0
                && getAdapter().isEnabled(motionPosition)) {
            mTouchMode = TOUCH_MODE_DOWN;

            mBeginClick = true;

            if (mPendingCheckForTap == null) {
                mPendingCheckForTap = new CheckForTap();
            }

            postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
        }

        mMotionPosition = motionPosition;
        invalidate();
        break;

    case MotionEvent.ACTION_MOVE: {
        final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
        if (index < 0) {
            Log.e(TAG, "onInterceptTouchEvent could not find pointer with id " + mActivePointerId
                    + " - did StaggeredGridView receive an inconsistent " + "event stream?");
            return false;
        }
        final float y = MotionEventCompat.getY(ev, index);
        final float dy = y - mLastTouchY + mTouchRemainderY;
        final int deltaY = (int) dy;
        mTouchRemainderY = dy - deltaY;

        if (Math.abs(dy) > mTouchSlop) {
            setTouchMode(TOUCH_MODE_DRAGGING);
        }

        if (mTouchMode == TOUCH_MODE_DRAGGING) {
            mLastTouchY = y;

            if (!trackMotionScroll(deltaY, true)) {
                // Break fling velocity if we impacted an edge.
                mVelocityTracker.clear();
            }
        }

        updateSelectorState();
    }
        break;

    case MotionEvent.ACTION_CANCEL:
        updateSelectorState();
        setPressed(false);
        View motionView = this.getChildAt(mMotionPosition - mFirstPosition);
        if (motionView != null) {
            motionView.setPressed(false);
        }
        final Handler handler = getHandler();
        if (handler != null) {
            handler.removeCallbacks(mPendingCheckForLongPress);
        }

        if (mTopEdge != null) {
            mTopEdge.onRelease();
            mBottomEdge.onRelease();
        }

        setTouchMode(TOUCH_MODE_IDLE);
        break;

    case MotionEvent.ACTION_UP: {
        mVelocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
        final float velocity = VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId);
        final int prevTouchMode = mTouchMode;
        if (Math.abs(velocity) > mFlingVelocity) { // TODO
            setTouchMode(TOUCH_MODE_FLINGING);
            mScroller.fling(0, 0, 0, (int) velocity, 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE);
            mLastTouchY = 0;
            ViewCompat.postInvalidateOnAnimation(this);
        } else {
            setTouchMode(TOUCH_MODE_IDLE);
        }

        if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
            // TODO : handle
            mTouchMode = TOUCH_MODE_TAP;
        } else {
            mTouchMode = TOUCH_MODE_REST;
        }

        switch (prevTouchMode) {
        case TOUCH_MODE_DOWN:
        case TOUCH_MODE_TAP:
        case TOUCH_MODE_DONE_WAITING:
            final View child = getChildAt(motionPosition - mFirstPosition);
            final float x = ev.getX();
            final boolean inList = x > getPaddingLeft() && x < getWidth() - getPaddingRight();
            if (child != null && !child.hasFocusable() && inList) {
                if (mTouchMode != TOUCH_MODE_DOWN) {
                    child.setPressed(false);
                }

                if (mPerformClick == null) {
                    invalidate();
                    mPerformClick = new PerformClick();
                }

                final PerformClick performClick = mPerformClick;
                performClick.mClickMotionPosition = motionPosition;
                performClick.rememberWindowAttachCount();

                if (mTouchMode == TOUCH_MODE_DOWN || mTouchMode == TOUCH_MODE_TAP) {
                    final Handler handlerTouch = getHandler();
                    if (handlerTouch != null) {
                        handlerTouch.removeCallbacks(mTouchMode == TOUCH_MODE_DOWN ? mPendingCheckForTap
                                : mPendingCheckForLongPress);
                    }

                    if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
                        mTouchMode = TOUCH_MODE_TAP;

                        layoutChildren(mDataChanged);
                        child.setPressed(true);
                        positionSelector(mMotionPosition, child);
                        setPressed(true);
                        if (mSelector != null) {
                            Drawable d = mSelector.getCurrent();
                            if (d != null && d instanceof TransitionDrawable) {
                                ((TransitionDrawable) d).resetTransition();
                            }
                        }
                        if (mTouchModeReset != null) {
                            removeCallbacks(mTouchModeReset);
                        }
                        mTouchModeReset = new Runnable() {
                            @Override
                            public void run() {
                                mTouchMode = TOUCH_MODE_REST;
                                child.setPressed(false);
                                setPressed(false);
                                if (!mDataChanged) {
                                    performClick.run();
                                }
                            }
                        };
                        postDelayed(mTouchModeReset, ViewConfiguration.getPressedStateDuration());

                    } else {
                        mTouchMode = TOUCH_MODE_REST;
                    }
                    return true;
                } else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
                    performClick.run();
                }
            }

            mTouchMode = TOUCH_MODE_REST;
        }
        mBeginClick = false;
        updateSelectorState();
    }
        break;
    }
    return true;
}

From source file:com.bahrini.pager.pager.RtlSupportViewPager.java

protected boolean isSwipeBlocked(MotionEvent event) {
    float deltaX = 0;

    switch (event.getAction()) {

    case MotionEvent.ACTION_UP:
        deltaX = mSwipeBlockedLastMotionX - event.getX();

        if (deltaX < 0) {
            /* is going to LEFT */
            if (!isSwipeLeft) {
                if (mCurItem <= mCutOffPage) {
                    return false;
                }/* w  ww .ja  v a  2  s.co  m*/
            }
            break;
        } else {
            /* is going to RIGHT */
            if (!isSwipeRight) {
                if (mCurItem >= mCutOffPage) {
                    return false;
                }
            }

            break;
        }

    default:
        break;
    }
    return true;
}

From source file:com.acbelter.scheduleview.ScheduleView.java

private void init(Context context) {
    if (!isInEditMode()) {
        mOverScroller = new OverScroller(context);
        mGestureListener = new GestureDetector.SimpleOnGestureListener() {
            @Override/*from  w  ww . j a v  a 2  s.  c  o  m*/
            public boolean onDown(MotionEvent e) {
                if (DEBUG) {
                    Log.d(TAG, "onDown() y=" + mListY);
                }

                releaseEdgeEffects();
                mOverScroller.forceFinished(true);
                return true;
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                if (DEBUG) {
                    Log.d(TAG, "onFling() y=" + mListY);
                }

                // Fling isn't needed
                if (mDeltaHeight < 0) {
                    return true;
                }

                mScrollDirection = velocityY > 0 ? 1 : -1;
                mOverScroller.fling(0, mListY, 0, (int) velocityY, 0, 0, -mDeltaHeight, 0);
                if (!awakenScrollBars()) {
                    ViewCompat.postInvalidateOnAnimation(ScheduleView.this);
                }
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                for (int i = 0; i < getChildCount(); i++) {
                    getChildAt(i).setPressed(false);
                }

                mListY -= (int) distanceY;
                recalculateOffset();

                positionItemViews();

                if (mListY == 0) {
                    mTopEdgeEffect.onPull(distanceY / (float) getHeight());
                    mTopEdgeEffectActive = true;
                }
                if (mListY == -mDeltaHeight) {
                    mBottomEdgeEffect.onPull(distanceY / (float) getHeight());
                    mBottomEdgeEffectActive = true;
                }

                if (!awakenScrollBars()) {
                    invalidate();
                }

                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                if (DEBUG) {
                    Log.d(TAG, "onLongPress() y=" + mListY);
                }

                View child;
                for (int i = 0; i < getChildCount(); i++) {
                    child = getChildAt(i);
                    child.getHitRect(mClickedViewBounds);
                    if (mClickedViewBounds.contains((int) e.getX(), (int) e.getY())) {
                        if (!mIsActionMode) {
                            mActionMode = startActionMode(mActionModeCallback);
                            mIsActionMode = true;
                        }

                        if (!child.isSelected()) {
                            mSelectedIds.add(mAdapter.getItemId(i));
                            child.setSelected(true);
                        } else {
                            mSelectedIds.remove(mAdapter.getItemId(i));
                            child.setSelected(false);
                        }

                        if (mSelectedIds.isEmpty()) {
                            finishActionMode();
                        }

                        invalidate();
                        return;
                    }
                }
            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (DEBUG) {
                    Log.d(TAG, "onSingleTapConfirmed() y=" + mListY);
                }

                View child;
                for (int i = 0; i < getChildCount(); i++) {
                    child = getChildAt(i);
                    child.getHitRect(mClickedViewBounds);
                    if (mClickedViewBounds.contains((int) e.getX(), (int) e.getY())) {
                        if (!mIsActionMode) {
                            OnItemClickListener callback = getOnItemClickListener();

                            if (callback != null) {
                                callback.onItemClick(ScheduleView.this, child, i, mAdapter.getItemId(i));
                            }
                        } else {
                            if (!child.isSelected()) {
                                mSelectedIds.add(mAdapter.getItemId(i));
                                child.setSelected(true);
                            } else {
                                mSelectedIds.remove(mAdapter.getItemId(i));
                                child.setSelected(false);
                            }

                            if (mSelectedIds.isEmpty()) {
                                finishActionMode();
                            }

                            invalidate();
                        }
                        break;
                    }
                }
                return true;
            }
        };

        mGestureDetector = new GestureDetector(context, mGestureListener);
    }
}

From source file:com.cssweb.android.view.KlineView.java

public void touchesMoved(MotionEvent event) {
    //Log.i("========currentPositionX==========", currentPositionX+">>>>>>>>>>");
    //Log.i("========currentPositionY==========", currentPositionY+">>>>>>>>>>");
    currentPositionX = event.getX();
    currentPositionY = event.getY();//from  ww w .  ja v  a2  s.c  o m
    float deltaX = startPositionX - currentPositionX;
    float deltaY = startPositionY - currentPositionY;
    //Log.i("========Math.abs(delta)==========", Math.abs(deltaX)+">>>>>>>>>>"+Math.abs(deltaY));
    if (Math.abs(deltaX) < 8 && Math.abs(deltaY) < 8) {
        isTouchMoved = false;
    } else {
        isTouchMoved = true;
    }
    if (quoteData == null)
        return;
    int mouseX = (int) event.getX();
    int mouseY = (int) event.getY();
    if (mouseX <= klineX || mouseY <= axisLabelHeight || mouseY >= height - axisLabelHeight - zbmenuHeight)
        return;

    if (isTrackStatus) {//??
        isSingleMoved = false;//???
        double sep = (shapeWidth + spaceWidth);
        visualPos = (int) ((mouseX - klineX) / sep + 1);
        if (visualPos >= this.actualDataLen - actualPos) {
            visualPos = this.actualDataLen - actualPos;
        } else if (visualPos < 1)
            visualPos = 1;
        int idx = actualPos + visualPos - 1;

        if (mouseX > klineX) {
            trackLineV = (int) (visualPos * (spaceWidth + shapeWidth) - shapeWidth / 2);
        }

        if (idx < actualDataLen) {
            isTrackNumber = idx;
        } else {
            isTrackNumber = this.actualDataLen - 1;
        }
        //         Log.i("@@@@@@@@@@isTrackNumber@@@@@@@@@@", isTrackNumber+">>>>>>>>>");
        //         Log.i("@@@@@@@@@@idx@@@@@@@@@@", idx+">>>>>>>>>");
        //         Log.i("@@@@@@@@@@actualPos@@@@@@@@@@", actualPos+">>>>>>>>>");
        //         Log.i("@@@@@@@@@@visualPos@@@@@@@@@@", visualPos+">>>>>>>>>");
        this.invalidate();
    } else {//K?
        isSingleMoved = true;
        if (deltaX < -50 && deltaY < 10) {
            moveRight(1);
        } else if (deltaX > 50 && deltaY < 10) {
            moveLeft(1);
        }
    }
}

From source file:com.cssweb.android.view.KlineView.java

public void touchesEnded(MotionEvent event) {
    isTouched = false;/* w  ww .j ava  2s.c o m*/
    if (isTouchMoved == false) {
        isTouchMoved = false;
        isTrackStatus = !isTrackStatus;
        if (isTrackStatus) {//??
            int mouseX = (int) event.getX();
            int mouseY = (int) event.getY();
            if (mouseX <= klineX || mouseY <= axisLabelHeight
                    || mouseY >= height - axisLabelHeight - zbmenuHeight)
                return;
            double sep = (shapeWidth + spaceWidth);
            visualPos = (int) ((mouseX - klineX) / sep + 1);
            if (visualPos >= this.actualDataLen - actualPos) {
                visualPos = this.actualDataLen - actualPos;
                isTrackNumber = actualDataLen - 1;
            } else {
                isTrackNumber = actualPos + visualPos - 1;
            }
            trackLineV = (int) (visualPos * (spaceWidth + shapeWidth) - shapeWidth / 2);
            //            Log.i("========isTouched222==========", trackLineV+">>>>>"+visualKLineCount+">>>>>" + isTrackNumber);
            //            Log.i("========isTouchMoved==========", actualDataLen+">>>>"+actualPos+">>>>>>" + visualPos);
        } else {
            isSingleMoved = true;
        }
    } else {

    }
    this.invalidate();
    //Log.i("========isTouched==========", isTouched+">>>>>>>>>>");
    //Log.i("========isTouchMoved==========", isTouchMoved+">>>>>>>>>>");
    //Log.i("========isTrackStatus==========", isTrackStatus+">>>>>>>>>>");
}

From source file:com.baidu.zhuanche.view.LazyViewPager.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (mFakeDragging) {
        // A fake drag is in progress already, ignore this real one
        // but still eat the touch events.
        // (It is likely that the user is multi-touching the screen.)
        return true;
    }/*  w ww  .  ja  va  2 s  .  com*/

    if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
        // Don't handle edge touches immediately -- they may actually belong to one of our
        // descendants.
        return false;
    }

    if (mAdapter == null || mAdapter.getCount() == 0) {
        // Nothing to present or scroll; nothing to touch.
        return false;
    }

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

    final int action = ev.getAction();
    boolean needsInvalidate = false;

    switch (action & MotionEventCompat.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: {
        /*
         * If being flinged and user touches, stop the fling. isFinished
         * will be false if being flinged.
         */
        completeScroll();

        // Remember where the motion event started
        mLastMotionX = mInitialMotionX = ev.getX();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    }
    case MotionEvent.ACTION_MOVE:
        if (!mIsBeingDragged) {
            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, pointerIndex);
            final float xDiff = Math.abs(x - mLastMotionX);
            final float y = MotionEventCompat.getY(ev, pointerIndex);
            final float yDiff = Math.abs(y - mLastMotionY);
            if (DEBUG)
                Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
            if (xDiff > mTouchSlop && xDiff > yDiff) {
                if (DEBUG)
                    Log.v(TAG, "Starting drag!");
                mIsBeingDragged = true;
                mLastMotionX = x;
                setScrollState(SCROLL_STATE_DRAGGING);
                setScrollingCacheEnabled(true);
            }
        }
        if (mIsBeingDragged) {
            // Scroll to follow the motion event
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float deltaX = mLastMotionX - x;
            mLastMotionX = x;
            float oldScrollX = getScrollX();
            float scrollX = oldScrollX + deltaX;
            final int width = getWidth();
            final int widthWithMargin = width + mPageMargin;

            final int lastItemIndex = mAdapter.getCount() - 1;
            final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin);
            final float rightBound = Math.min(mCurItem + 1, lastItemIndex) * widthWithMargin;
            if (scrollX < leftBound) {
                if (leftBound == 0) {
                    float over = -scrollX;
                    needsInvalidate = mLeftEdge.onPull(over / width);
                }
                scrollX = leftBound;
            } else if (scrollX > rightBound) {
                if (rightBound == lastItemIndex * widthWithMargin) {
                    float over = scrollX - rightBound;
                    needsInvalidate = mRightEdge.onPull(over / width);
                }
                scrollX = rightBound;
            }
            // Don't lose the rounded component
            mLastMotionX += scrollX - (int) scrollX;
            scrollTo((int) scrollX, getScrollY());
            pageScrolled((int) scrollX);
        }
        break;
    case MotionEvent.ACTION_UP:
        if (mIsBeingDragged) {
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker, mActivePointerId);
            mPopulatePending = true;
            final int widthWithMargin = getWidth() + mPageMargin;
            final int scrollX = getScrollX();
            final int currentPage = scrollX / widthWithMargin;
            final float pageOffset = (float) (scrollX % widthWithMargin) / widthWithMargin;
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final int totalDelta = (int) (x - mInitialMotionX);
            int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta);
            setCurrentItemInternal(nextPage, true, true, initialVelocity);

            mActivePointerId = INVALID_POINTER;
            endDrag();
            needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsBeingDragged) {
            setCurrentItemInternal(mCurItem, true, true);
            mActivePointerId = INVALID_POINTER;
            endDrag();
            needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
        }
        break;
    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        final float x = MotionEventCompat.getX(ev, index);
        mLastMotionX = x;
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }
    if (needsInvalidate) {
        invalidate();
    }
    return true;
}

From source file:beichen.douban.ui.view.LazyViewPager.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (mFakeDragging) {
        // A fake drag is in progress already, ignore this real one
        // but still eat the touch events.
        // (It is likely that the user is multi-touching the screen.)
        return true;
    }//  w  ww . ja va 2s.  co  m

    if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
        // Don't handle edge touches immediately -- they may actually belong
        // to one of our
        // descendants.
        return false;
    }

    if (mAdapter == null || mAdapter.getCount() == 0) {
        // Nothing to present or scroll; nothing to touch.
        return false;
    }

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

    final int action = ev.getAction();
    boolean needsInvalidate = false;

    switch (action & MotionEventCompat.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: {
        /*
         * If being flinged and user touches, stop the fling. isFinished
         * will be false if being flinged.
         */
        completeScroll();

        // Remember where the motion event started
        mLastMotionX = mInitialMotionX = ev.getX();
        mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
        break;
    }
    case MotionEvent.ACTION_MOVE:
        if (!mIsBeingDragged) {
            final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, pointerIndex);
            final float xDiff = Math.abs(x - mLastMotionX);
            final float y = MotionEventCompat.getY(ev, pointerIndex);
            final float yDiff = Math.abs(y - mLastMotionY);
            if (DEBUG)
                Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
            if (xDiff > mTouchSlop && xDiff > yDiff) {
                if (DEBUG)
                    Log.v(TAG, "Starting drag!");
                mIsBeingDragged = true;
                mLastMotionX = x;
                setScrollState(SCROLL_STATE_DRAGGING);
                setScrollingCacheEnabled(true);
            }
        }
        if (mIsBeingDragged) {
            // Scroll to follow the motion event
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final float deltaX = mLastMotionX - x;
            mLastMotionX = x;
            float oldScrollX = getScrollX();
            float scrollX = oldScrollX + deltaX;
            final int width = getWidth();
            final int widthWithMargin = width + mPageMargin;

            final int lastItemIndex = mAdapter.getCount() - 1;
            final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin);
            final float rightBound = Math.min(mCurItem + 1, lastItemIndex) * widthWithMargin;
            if (scrollX < leftBound) {
                if (leftBound == 0) {
                    float over = -scrollX;
                    needsInvalidate = mLeftEdge.onPull(over / width);
                }
                scrollX = leftBound;
            } else if (scrollX > rightBound) {
                if (rightBound == lastItemIndex * widthWithMargin) {
                    float over = scrollX - rightBound;
                    needsInvalidate = mRightEdge.onPull(over / width);
                }
                scrollX = rightBound;
            }
            // Don't lose the rounded component
            mLastMotionX += scrollX - (int) scrollX;
            scrollTo((int) scrollX, getScrollY());
            pageScrolled((int) scrollX);
        }
        break;
    case MotionEvent.ACTION_UP:
        if (mIsBeingDragged) {
            final VelocityTracker velocityTracker = mVelocityTracker;
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
            int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker, mActivePointerId);
            mPopulatePending = true;
            final int widthWithMargin = getWidth() + mPageMargin;
            final int scrollX = getScrollX();
            final int currentPage = scrollX / widthWithMargin;
            final float pageOffset = (float) (scrollX % widthWithMargin) / widthWithMargin;
            final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
            final float x = MotionEventCompat.getX(ev, activePointerIndex);
            final int totalDelta = (int) (x - mInitialMotionX);
            int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta);
            setCurrentItemInternal(nextPage, true, true, initialVelocity);

            mActivePointerId = INVALID_POINTER;
            endDrag();
            needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        if (mIsBeingDragged) {
            setCurrentItemInternal(mCurItem, true, true);
            mActivePointerId = INVALID_POINTER;
            endDrag();
            needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
        }
        break;
    case MotionEventCompat.ACTION_POINTER_DOWN: {
        final int index = MotionEventCompat.getActionIndex(ev);
        final float x = MotionEventCompat.getX(ev, index);
        mLastMotionX = x;
        mActivePointerId = MotionEventCompat.getPointerId(ev, index);
        break;
    }
    case MotionEventCompat.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
        break;
    }
    if (needsInvalidate) {
        invalidate();
    }
    return true;
}

From source file:com.android.ex.chips.RecipientEditTextView.java

/**
 * Monitor touch events in the RecipientEditTextView. If the view does not have focus, any tap on the view will just
 * focus the view. If the view has focus, determine if the touch target is a recipient chip. If it is and the chip
 * is not selected, select it and clear any other selected chips. If it isn't, then select that chip.
 *//*from  w  w  w . j  ava2  s.com*/
@Override
public boolean onTouchEvent(final MotionEvent event) {
    if (!isFocused())
        // Ignore any chip taps until this view is focused.
        return super.onTouchEvent(event);
    android.util.Log.d("AppLog", "scroll:" + getScrollY());
    boolean handled = super.onTouchEvent(event);
    final int action = event.getAction();
    boolean chipWasSelected = false;
    if (mSelectedChip == null)
        mGestureDetector.onTouchEvent(event);
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        mIsScrolling = false;
        mStartTouchY = (int) event.getY();
        break;
    case MotionEvent.ACTION_MOVE:
        if (Math.abs(event.getY() - mStartTouchY) > SCROLLING_BOUNDS_THRESHOLD_IN_PIXELS)
            mIsScrolling = true;
        break;
    case MotionEvent.ACTION_UP:
        if (mIsScrolling) {
            mIsScrolling = false;
            break;
        }
        if (mCopyAddress == null) {
            final float x = event.getX();
            final float y = event.getY();
            final int offset = putOffsetInRange(x, y);
            final DrawableRecipientChip currentChip = findChip(offset);
            if (currentChip != null) {
                if (action == MotionEvent.ACTION_UP)
                    if (mSelectedChip != null && mSelectedChip != currentChip) {
                        clearSelectedChip();
                        mSelectedChip = selectChip(currentChip);
                    } else if (mSelectedChip == null) {
                        setSelection(getText().length());
                        commitDefault();
                        mSelectedChip = selectChip(currentChip);
                    } else
                        onClick(mSelectedChip, offset, x, y);
                chipWasSelected = true;
                handled = true;
            } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip))
                chipWasSelected = true;
        }
        if (!chipWasSelected)
            clearSelectedChip();
        break;
    }
    return handled;
}

From source file:caesar.feng.framework.widget.StaggeredGrid.ExtendableListView.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    int action = ev.getAction();

    if (!mIsAttached) {
        // Something isn't right.
        // Since we rely on being attached to get data set change notifications,
        // don't risk doing anything where we might try to resync and find things
        // in a bogus state.
        return false;
    }/*w  w w.j av a2s . c  o m*/

    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN: {
        int touchMode = mTouchMode;

        // TODO : overscroll
        //                if (touchMode == TOUCH_MODE_OVERFLING || touchMode == TOUCH_MODE_OVERSCROLL) {
        //                    mMotionCorrection = 0;
        //                    return true;
        //                }

        final int x = (int) ev.getX();
        final int y = (int) ev.getY();
        mActivePointerId = ev.getPointerId(0);

        int motionPosition = findMotionRow(y);
        if (touchMode != TOUCH_MODE_FLINGING && motionPosition >= 0) {
            // User clicked on an actual view (and was not stopping a fling).
            // Remember where the motion event started
            mMotionX = x;
            mMotionY = y;
            mMotionPosition = motionPosition;
            mTouchMode = TOUCH_MODE_DOWN;
        }
        mLastY = Integer.MIN_VALUE;
        initOrResetVelocityTracker();
        mVelocityTracker.addMovement(ev);
        if (touchMode == TOUCH_MODE_FLINGING) {
            return true;
        }
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        switch (mTouchMode) {
        case TOUCH_MODE_DOWN:
            int pointerIndex = ev.findPointerIndex(mActivePointerId);
            if (pointerIndex == -1) {
                pointerIndex = 0;
                mActivePointerId = ev.getPointerId(pointerIndex);
            }
            final int y = (int) ev.getY(pointerIndex);
            initVelocityTrackerIfNotExists();
            mVelocityTracker.addMovement(ev);
            if (startScrollIfNeeded(y)) {
                return true;
            }
            break;
        }
        break;
    }

    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP: {
        mTouchMode = TOUCH_MODE_IDLE;
        mActivePointerId = INVALID_POINTER;
        recycleVelocityTracker();
        reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
        break;
    }

    case MotionEvent.ACTION_POINTER_UP: {
        onSecondaryPointerUp(ev);
        break;
    }
    }

    return false;
}

From source file:com.android.launcher2.PagedView.java

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    /*//w ww  .  ja va  2  s  .c  o m
     * This method JUST determines whether we want to intercept the motion.
     * If we return true, onTouchEvent will be called and we do the actual
     * scrolling there.
     */
    acquireVelocityTrackerAndAddMovement(ev);

    // Skip touch handling if there are no pages to swipe
    if (getChildCount() <= 0)
        return super.onInterceptTouchEvent(ev);

    /*
     * Shortcut the most recurring case: the user is in the dragging
     * state and he is moving his finger.  We want to intercept this
     * motion.
     */
    final int action = ev.getAction();
    if ((action == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) {
        return true;
    }

    switch (action & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_MOVE: {
        /*
         * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
         * whether the user has moved far enough from his original down touch.
         */
        if (mActivePointerId != INVALID_POINTER) {
            determineScrollingStart(ev);
            break;
        }
        // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
        // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
        // i.e. fall through to the next case (don't break)
        // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
        // while it's small- this was causing a crash before we checked for INVALID_POINTER)
    }

    case MotionEvent.ACTION_DOWN: {
        final float x = ev.getX();
        final float y = ev.getY();
        // Remember location of down touch
        mDownMotionX = x;
        mLastMotionX = x;
        mLastMotionY = y;
        mLastMotionXRemainder = 0;
        mTotalMotionX = 0;
        mActivePointerId = ev.getPointerId(0);
        mAllowLongPress = true;

        /*
         * If being flinged and user touches the screen, initiate drag;
         * otherwise don't.  mScroller.isFinished should be false when
         * being flinged.
         */
        final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
        final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
        if (finishedScrolling) {
            mTouchState = TOUCH_STATE_REST;
            mScroller.abortAnimation();
        } else {
            mTouchState = TOUCH_STATE_SCROLLING;
        }

        // check if this can be the beginning of a tap on the side of the pages
        // to scroll the current page
        if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
            if (getChildCount() > 0) {
                if (hitsPreviousPage(x, y)) {
                    mTouchState = TOUCH_STATE_PREV_PAGE;
                } else if (hitsNextPage(x, y)) {
                    mTouchState = TOUCH_STATE_NEXT_PAGE;
                }
            }
        }
        break;
    }

    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
        mTouchState = TOUCH_STATE_REST;
        mAllowLongPress = false;
        mActivePointerId = INVALID_POINTER;
        releaseVelocityTracker();
        break;

    case MotionEvent.ACTION_POINTER_UP:
        onSecondaryPointerUp(ev);
        releaseVelocityTracker();
        break;
    }

    /*
     * The only time we want to intercept motion events is if we are in the
     * drag mode.
     */
    return mTouchState != TOUCH_STATE_REST;
}