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(int pointerIndex) 

Source Link

Document

Returns the X coordinate of this event for the given pointer index (use #getPointerId(int) to find the pointer identifier for this index).

Usage

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

/**
 * true?,false??/*from   w w  w  .  j  a v a2s .c o  m*/
 */
public boolean onTouchEvent(MotionEvent motionEvent) {
    int count = motionEvent.getPointerCount();
    if (count == 2) {//
        isTrackStatus = false;
        if (motionEvent.getAction() == MotionEvent.ACTION_POINTER_1_DOWN
                || motionEvent.getAction() == MotionEvent.ACTION_POINTER_2_DOWN) {
            float x0 = motionEvent.getX(0);
            float x1 = motionEvent.getX(1);
            float y0 = motionEvent.getY(0);
            float y1 = motionEvent.getY(1);
            distanceY0 = Math.abs(y1 - y0);
            distanceX0 = Math.abs(x1 - x0);
        }
        if (motionEvent.getAction() == MotionEvent.ACTION_POINTER_1_UP
                || motionEvent.getAction() == MotionEvent.ACTION_POINTER_2_UP) {
            float x0 = motionEvent.getX(0);
            float x1 = motionEvent.getX(1);
            float y0 = motionEvent.getY(0);
            float y1 = motionEvent.getY(1);
            distanceY1 = Math.abs(y1 - y0);
            distanceX1 = Math.abs(x1 - x0);
            if (distanceY1 > distanceY0 && distanceX1 > distanceX0) {
                upHandler();
            } else if (distanceY1 < distanceY0 && distanceX1 < distanceX0) {
                downHandler();
            }
        }
        return false;
    } else if (count == 1) {//??
        switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touchesBegan(motionEvent);
            break;

        case MotionEvent.ACTION_MOVE:
            touchesMoved(motionEvent);
            break;

        case MotionEvent.ACTION_UP:
            touchesEnded(motionEvent);
            break;

        }
    }
    return true;
}

From source file:com.bizcom.vc.widget.cus.SubsamplingScaleImageView.java

/**
 * Handle touch events. One finger pans, and two finger pinch and zoom plus
 * panning.//w  w w . ja  v  a2  s.  c om
 */
@Override
public boolean onTouchEvent(MotionEvent event) {
    PointF vCenterEnd;
    float vDistEnd;
    // During non-interruptible anims, ignore all touch events
    if (anim != null && !anim.interruptible) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return true;
    } else {
        anim = null;
    }

    // Abort if not ready
    if (vTranslate == null) {
        return true;
    }
    // Detect flings, taps and double taps
    if (detector == null || detector.onTouchEvent(event)) {
        return true;
    }

    int touchCount = event.getPointerCount();
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_POINTER_1_DOWN:
    case MotionEvent.ACTION_POINTER_2_DOWN:
        anim = null;
        getParent().requestDisallowInterceptTouchEvent(true);
        maxTouchCount = Math.max(maxTouchCount, touchCount);
        if (touchCount >= 2) {
            if (zoomEnabled) {
                // Start pinch to zoom. Calculate distance between touch
                // points and center point of the pinch.
                float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1));
                scaleStart = scale;
                vDistStart = distance;
                vTranslateStart = new PointF(vTranslate.x, vTranslate.y);
                vCenterStart = new PointF((event.getX(0) + event.getX(1)) / 2,
                        (event.getY(0) + event.getY(1)) / 2);
            } else {
                // Abort all gestures on second touch
                maxTouchCount = 0;
            }
            // Cancel long click timer
            handler.removeMessages(MESSAGE_LONG_CLICK);
        } else {
            // Start one-finger pan
            vTranslateStart = new PointF(vTranslate.x, vTranslate.y);
            vCenterStart = new PointF(event.getX(), event.getY());

            // Start long click timer
            handler.sendEmptyMessageDelayed(MESSAGE_LONG_CLICK, 600);
        }
        return true;
    case MotionEvent.ACTION_MOVE:
        boolean consumed = false;
        if (maxTouchCount > 0) {
            if (touchCount >= 2) {
                // Calculate new distance between touch points, to scale and
                // pan relative to start values.
                vDistEnd = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1));
                vCenterEnd = new PointF((event.getX(0) + event.getX(1)) / 2,
                        (event.getY(0) + event.getY(1)) / 2);

                if (zoomEnabled && (distance(vCenterStart.x, vCenterEnd.x, vCenterStart.y, vCenterEnd.y) > 5
                        || Math.abs(vDistEnd - vDistStart) > 5 || isPanning)) {
                    isZooming = true;
                    isPanning = true;
                    consumed = true;

                    scale = Math.min(maxScale, (vDistEnd / vDistStart) * scaleStart);

                    if (scale <= minScale()) {
                        // Minimum scale reached so don't pan. Adjust start
                        // settings so any expand will zoom in.
                        vDistStart = vDistEnd;
                        scaleStart = minScale();
                        vCenterStart = vCenterEnd;
                        vTranslateStart = vTranslate;
                    } else if (panEnabled) {
                        // Translate to place the source image coordinate
                        // that was at the center of the pinch at the start
                        // at the center of the pinch now, to give
                        // simultaneous pan + zoom.
                        float vLeftStart = vCenterStart.x - vTranslateStart.x;
                        float vTopStart = vCenterStart.y - vTranslateStart.y;
                        float vLeftNow = vLeftStart * (scale / scaleStart);
                        float vTopNow = vTopStart * (scale / scaleStart);
                        vTranslate.x = vCenterEnd.x - vLeftNow;
                        vTranslate.y = vCenterEnd.y - vTopNow;
                    } else if (sRequestedCenter != null) {
                        // With a center specified from code, zoom around
                        // that point.
                        vTranslate.x = (getWidth() / 2) - (scale * sRequestedCenter.x);
                        vTranslate.y = (getHeight() / 2) - (scale * sRequestedCenter.y);
                    } else {
                        // With no requested center, scale around the image
                        // center.
                        vTranslate.x = (getWidth() / 2) - (scale * (sWidth() / 2));
                        vTranslate.y = (getHeight() / 2) - (scale * (sHeight() / 2));
                    }

                    fitToBounds(true);
                    refreshRequiredTiles(false);
                }
            } else if (!isZooming) {
                // One finger pan - translate the image. We do this
                // calculation even with pan disabled so click
                // and long click behaviour is preserved.
                float dx = Math.abs(event.getX() - vCenterStart.x);
                float dy = Math.abs(event.getY() - vCenterStart.y);
                if (dx > 5 || dy > 5 || isPanning) {
                    consumed = true;
                    vTranslate.x = vTranslateStart.x + (event.getX() - vCenterStart.x);
                    vTranslate.y = vTranslateStart.y + (event.getY() - vCenterStart.y);

                    float lastX = vTranslate.x;
                    float lastY = vTranslate.y;
                    fitToBounds(true);
                    if (lastX == vTranslate.x || (lastY == vTranslate.y && dy > 10) || isPanning) {
                        isPanning = true;
                    } else if (dx > 5) {
                        // Haven't panned the image, and we're at the left
                        // or right edge. Switch to page swipe.
                        maxTouchCount = 0;
                        handler.removeMessages(MESSAGE_LONG_CLICK);
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }

                    if (!panEnabled) {
                        vTranslate.x = vTranslateStart.x;
                        vTranslate.y = vTranslateStart.y;
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }

                    refreshRequiredTiles(false);
                }
            }
        }
        if (consumed) {
            handler.removeMessages(MESSAGE_LONG_CLICK);
            invalidate();
            return true;
        }
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_POINTER_UP:
    case MotionEvent.ACTION_POINTER_2_UP:
        handler.removeMessages(MESSAGE_LONG_CLICK);
        if (maxTouchCount > 0 && (isZooming || isPanning)) {
            if (isZooming && touchCount == 2) {
                // Convert from zoom to pan with remaining touch
                isPanning = true;
                vTranslateStart = new PointF(vTranslate.x, vTranslate.y);
                if (event.getActionIndex() == 1) {
                    vCenterStart = new PointF(event.getX(0), event.getY(0));
                } else {
                    vCenterStart = new PointF(event.getX(1), event.getY(1));
                }
            }
            if (touchCount < 3) {
                // End zooming when only one touch point
                isZooming = false;
            }
            if (touchCount < 2) {
                // End panning when no touch points
                isPanning = false;
                maxTouchCount = 0;
            }
            // Trigger load of tiles now required
            refreshRequiredTiles(true);
            return true;
        }
        if (touchCount == 1) {
            isZooming = false;
            isPanning = false;
            maxTouchCount = 0;
        }
        return true;
    }
    return super.onTouchEvent(event);
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardBaseView.java

@Override
public boolean onTouchEvent(MotionEvent nativeMotionEvent) {
    if (mKeyboard == null)//I mean, if there isn't any keyboard I'm handling, what's the point?
        return false;
    final int action = MotionEventCompat.getActionMasked(nativeMotionEvent);
    final int pointerCount = MotionEventCompat.getPointerCount(nativeMotionEvent);
    final int oldPointerCount = mOldPointerCount;
    mOldPointerCount = pointerCount;//from   ww  w .  j  a  v  a  2 s  .co m
    if (pointerCount > 1)
        mLastTimeHadTwoFingers = SystemClock.elapsedRealtime();//marking the time. Read isAtTwoFingersState()

    if (mTouchesAreDisabledTillLastFingerIsUp) {
        if (mOldPointerCount == 1 && (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP)) {
            mTouchesAreDisabledTillLastFingerIsUp = false;
        }

        return true;
    }
    // TODO: cleanup this code into a multi-touch to single-touch event
    // converter class?
    // If the device does not have distinct multi-touch support panel,
    // ignore all multi-touch
    // events except a transition from/to single-touch.
    if (!mHasDistinctMultitouch && pointerCount > 1 && oldPointerCount > 1) {
        return true;
    }

    // Gesture detector must be enabled only when mini-keyboard is not
    // on the screen.
    if (!mMiniKeyboardVisible && mGestureDetector != null
            && (mGestureDetector.onTouchEvent(nativeMotionEvent))) {
        Log.d(TAG, "Gesture detected!");
        mHandler.cancelKeyTimers();
        dismissKeyPreview();
        return true;
    }

    final long eventTime = nativeMotionEvent.getEventTime();
    final int index = MotionEventCompat.getActionIndex(nativeMotionEvent);
    final int id = nativeMotionEvent.getPointerId(index);
    final int x = (int) nativeMotionEvent.getX(index);
    final int y = (int) nativeMotionEvent.getY(index);

    // Needs to be called after the gesture detector gets a turn, as it
    // may have
    // displayed the mini keyboard
    if (mMiniKeyboard != null && mMiniKeyboardVisible) {
        final int miniKeyboardPointerIndex = nativeMotionEvent.findPointerIndex(mMiniKeyboardTrackerId);
        if (miniKeyboardPointerIndex >= 0 && miniKeyboardPointerIndex < pointerCount) {
            final int miniKeyboardX = (int) nativeMotionEvent.getX(miniKeyboardPointerIndex);
            final int miniKeyboardY = (int) nativeMotionEvent.getY(miniKeyboardPointerIndex);
            MotionEvent translated = generateMiniKeyboardMotionEvent(action, miniKeyboardX, miniKeyboardY,
                    eventTime);
            mMiniKeyboard.onTouchEvent(translated);
            translated.recycle();
        }
        return true;
    }

    if (mHandler.isInKeyRepeat()) {
        // It will keep being in the key repeating mode while the key is
        // being pressed.
        if (action == MotionEvent.ACTION_MOVE) {
            return true;
        }
        final PointerTracker tracker = getPointerTracker(id);
        // Key repeating timer will be canceled if 2 or more keys are in
        // action, and current
        // event (UP or DOWN) is non-modifier key.
        if (pointerCount > 1 && !tracker.isModifier()) {
            mHandler.cancelKeyRepeatTimer();
        }
        // Up event will pass through.
    }

    // TODO: cleanup this code into a multi-touch to single-touch event
    // converter class?
    // Translate mutli-touch event to single-touch events on the device
    // that has no distinct
    // multi-touch panel.
    if (!mHasDistinctMultitouch) {
        // Use only main (id=0) pointer tracker.
        PointerTracker tracker = getPointerTracker(0);
        if (pointerCount == 1 && oldPointerCount == 2) {
            // Multi-touch to single touch transition.
            // Send a down event for the latest pointer.
            tracker.onDownEvent(x, y, eventTime);
        } else if (pointerCount == 2 && oldPointerCount == 1) {
            // Single-touch to multi-touch transition.
            // Send an up event for the last pointer.
            tracker.onUpEvent(tracker.getLastX(), tracker.getLastY(), eventTime);
        } else if (pointerCount == 1 && oldPointerCount == 1) {
            tracker.onTouchEvent(action, x, y, eventTime);
        } else {
            Log.w(TAG, "Unknown touch panel behavior: pointer count is " + pointerCount + " (old "
                    + oldPointerCount + ")");
        }
        return true;
    }

    if (action == MotionEvent.ACTION_MOVE) {
        for (int i = 0; i < pointerCount; i++) {
            PointerTracker tracker = getPointerTracker(nativeMotionEvent.getPointerId(i));
            tracker.onMoveEvent((int) nativeMotionEvent.getX(i), (int) nativeMotionEvent.getY(i), eventTime);
        }
    } else {
        PointerTracker tracker = getPointerTracker(id);
        sendOnXEvent(action, eventTime, x, y, tracker);
    }

    return true;
}

From source file:cc.flydev.launcher.Workspace.java

protected void onWallpaperTap(MotionEvent ev) {
    final int[] position = mTempCell;
    getLocationOnScreen(position);//  w  w  w  .  j av  a  2s .c o m

    int pointerIndex = ev.getActionIndex();
    position[0] += (int) ev.getX(pointerIndex);
    position[1] += (int) ev.getY(pointerIndex);

    mWallpaperManager.sendWallpaperCommand(getWindowToken(),
            ev.getAction() == MotionEvent.ACTION_UP ? WallpaperManager.COMMAND_TAP
                    : WallpaperManager.COMMAND_SECONDARY_TAP,
            position[0], position[1], 0, null);
}

From source file:com.android.internal.widget.ViewPager.java

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

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

    // Always take care of the touch gesture being complete.
    if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
        // Release the drag.
        if (DEBUG)
            Log.v(TAG, "Intercept done!");
        mIsBeingDragged = false;
        mIsUnableToDrag = false;
        mActivePointerId = INVALID_POINTER;
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
        return false;
    }

    // Nothing more to do here if we have decided whether or not we
    // are dragging.
    if (action != MotionEvent.ACTION_DOWN) {
        if (mIsBeingDragged) {
            if (DEBUG)
                Log.v(TAG, "Being dragged, intercept returning true!");
            return true;
        }
        if (mIsUnableToDrag) {
            if (DEBUG)
                Log.v(TAG, "Unable to drag, intercept returning false!");
            return false;
        }
    }

    switch (action) {
    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.
         */

        /*
        * Locally do absolute value. mLastMotionY is set to the y value
        * of the down event.
        */
        final int activePointerId = mActivePointerId;
        if (activePointerId == INVALID_POINTER) {
            // If we don't have a valid id, the touch down wasn't on content.
            break;
        }

        final int pointerIndex = ev.findPointerIndex(activePointerId);
        final float x = ev.getX(pointerIndex);
        final float dx = x - mLastMotionX;
        final float xDiff = Math.abs(dx);
        final float y = ev.getY(pointerIndex);
        final float yDiff = Math.abs(y - mInitialMotionY);
        if (DEBUG)
            Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);

        if (dx != 0 && !isGutterDrag(mLastMotionX, dx) && canScroll(this, false, (int) dx, (int) x, (int) y)) {
            // Nested view has scrollable area under this point. Let it be handled there.
            mLastMotionX = x;
            mLastMotionY = y;
            mIsUnableToDrag = true;
            return false;
        }
        if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) {
            if (DEBUG)
                Log.v(TAG, "Starting drag!");
            mIsBeingDragged = true;
            requestParentDisallowInterceptTouchEvent(true);
            setScrollState(SCROLL_STATE_DRAGGING);
            mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop : mInitialMotionX - mTouchSlop;
            mLastMotionY = y;
            setScrollingCacheEnabled(true);
        } else if (yDiff > mTouchSlop) {
            // The finger has moved enough in the vertical
            // direction to be counted as a drag...  abort
            // any attempt to drag horizontally, to work correctly
            // with children that have scrolling containers.
            if (DEBUG)
                Log.v(TAG, "Starting unable to drag!");
            mIsUnableToDrag = true;
        }
        if (mIsBeingDragged) {
            // Scroll to follow the motion event
            if (performDrag(x)) {
                postInvalidateOnAnimation();
            }
        }
        break;
    }

    case MotionEvent.ACTION_DOWN: {
        /*
         * Remember location of down touch.
         * ACTION_DOWN always refers to pointer index 0.
         */
        mLastMotionX = mInitialMotionX = ev.getX();
        mLastMotionY = mInitialMotionY = ev.getY();
        mActivePointerId = ev.getPointerId(0);
        mIsUnableToDrag = false;

        mScroller.computeScrollOffset();
        if (mScrollState == SCROLL_STATE_SETTLING
                && Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) {
            // Let the user 'catch' the pager as it animates.
            mScroller.abortAnimation();
            mPopulatePending = false;
            populate();
            mIsBeingDragged = true;
            requestParentDisallowInterceptTouchEvent(true);
            setScrollState(SCROLL_STATE_DRAGGING);
        } else {
            completeScroll(false);
            mIsBeingDragged = false;
        }

        if (DEBUG)
            Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY + " mIsBeingDragged=" + mIsBeingDragged
                    + "mIsUnableToDrag=" + mIsUnableToDrag);
        break;
    }

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

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

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

From source file:com.appunite.list.AbsHorizontalListView.java

private void onSecondaryPointerUp(MotionEvent ev) {
    final int pointerIndex = (ev.getAction()
            & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
    final int pointerId = ev.getPointerId(pointerIndex);
    if (pointerId == mActivePointerId) {
        // This was our active pointer going up. Choose a new
        // active pointer and adjust accordingly.
        // TODO: Make this decision more intelligent.
        final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
        mMotionX = (int) ev.getX(newPointerIndex);
        mMotionY = (int) ev.getY(newPointerIndex);
        mMotionCorrection = 0;/*from   ww w  .  j  a  v  a  2s.  c om*/
        mActivePointerId = ev.getPointerId(newPointerIndex);
    }
}

From source file:cn.ismartv.tvrecyclerview.widget.RecyclerView.java

private void onPointerUp(MotionEvent e) {
    final int actionIndex = MotionEventCompat.getActionIndex(e);
    if (e.getPointerId(actionIndex) == mScrollPointerId) {
        // Pick a new pointer to pick up the slack.
        final int newIndex = actionIndex == 0 ? 1 : 0;
        mScrollPointerId = e.getPointerId(newIndex);
        mInitialTouchX = mLastTouchX = (int) (e.getX(newIndex) + 0.5f);
        mInitialTouchY = mLastTouchY = (int) (e.getY(newIndex) + 0.5f);
    }//from w  w  w  . j  a v a2  s  .  com
}