Example usage for android.view MotionEvent obtain

List of usage examples for android.view MotionEvent obtain

Introduction

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

Prototype

static public MotionEvent obtain(long downTime, long eventTime, int action, float x, float y, int metaState) 

Source Link

Document

Create a new MotionEvent, filling in a subset of the basic motion values.

Usage

From source file:com.onyx.latinime.accessibility.AccessibilityEntityProvider.java

/**
 * Simulates a key press by injecting touch events into the keyboard view.
 * This avoids the complexity of trackers and listeners within the keyboard.
 *
 * @param key The key to press.//  w w  w  .  jav a2 s .c o m
 */
void simulateKeyPress(final Key key) {
    final int x = key.getHitBox().centerX();
    final int y = key.getHitBox().centerY();
    final long downTime = SystemClock.uptimeMillis();
    final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0);
    final MotionEvent upEvent = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
            x, y, 0);

    mKeyboardView.onTouchEvent(downEvent);
    mKeyboardView.onTouchEvent(upEvent);
    downEvent.recycle();
    upEvent.recycle();
}

From source file:io.selendroid.server.model.AndroidWebElement.java

@Override
public void click() {
    String tagName = getTagName();
    if ((tagName != null && "OPTION".equals(tagName.toUpperCase())) || driver.isInFrame()) {
        driver.resetPageIsLoading();//from w w  w.j  a  v  a  2s .c  o m
        driver.executeAtom(AndroidAtoms.CLICK, null, this);
        driver.waitForPageToLoad();
        if (driver.isInFrame()) {
            return;
        }
    }

    Point center = getCenterCoordinates();
    long downTime = SystemClock.uptimeMillis();
    final List<MotionEvent> events = new ArrayList<MotionEvent>();

    MotionEvent downEvent = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
            center.x, center.y, 0);
    events.add(downEvent);
    MotionEvent upEvent = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
            center.x, center.y, 0);

    events.add(upEvent);

    driver.resetPageIsLoading();
    driver.getMotionSender().send(events);

    // If the page started loading we should wait
    // until the page is done loading.
    driver.waitForPageToLoad();
}

From source file:com.android.inputmethod.accessibility.KeyboardAccessibilityDelegate.java

/**
 * Simulating a touch event by injecting a synthesized touch event into {@link KeyboardView}.
 *
 * @param touchAction The action of the synthesizing touch event.
 * @param key The key that a synthesized touch event is on.
 *//*  w  w w  .  j  ava 2s.com*/
private void simulateTouchEvent(final int touchAction, final Key key) {
    final int x = key.getHitBox().centerX();
    final int y = key.getHitBox().centerY();
    final long eventTime = SystemClock.uptimeMillis();
    final MotionEvent touchEvent = MotionEvent.obtain(eventTime, eventTime, touchAction, x, y,
            0 /* metaState */);
    mKeyboardView.onTouchEvent(touchEvent);
    touchEvent.recycle();
}

From source file:com.yek.keyboard.keyboards.views.AnyKeyboardView.java

@Override
public boolean onTouchEvent(@NonNull MotionEvent me) {
    if (getKeyboard() == null)//I mean, if there isn't any keyboard I'm handling, what's the point?
        return false;

    if (areTouchesDisabled(me)) {
        return super.onTouchEvent(me);
    }//from  w  ww.  jav  a  2  s. c  o  m

    final int action = MotionEventCompat.getActionMasked(me);

    // Gesture detector must be enabled only when mini-keyboard is not
    // on the screen.
    if (!mMiniKeyboardPopup.isShowing() && mGestureDetector != null && mGestureDetector.onTouchEvent(me)) {
        Logger.d(TAG, "Gesture detected!");
        mKeyPressTimingHandler.cancelAllMessages();
        dismissAllKeyPreviews();
        return true;
    }

    if (action == MotionEvent.ACTION_DOWN) {
        mFirstTouchPoint.x = (int) me.getX();
        mFirstTouchPoint.y = (int) me.getY();
        mIsFirstDownEventInsideSpaceBar = mSpaceBarKey != null
                && mSpaceBarKey.isInside(mFirstTouchPoint.x, mFirstTouchPoint.y);
    }
    // If the motion event is above the keyboard and it's a MOVE event
    // coming even before the first MOVE event into the extension area
    if (!mIsFirstDownEventInsideSpaceBar && me.getY() < mExtensionKeyboardYActivationPoint
            && !mMiniKeyboardPopup.isShowing() && !mExtensionVisible && action == MotionEvent.ACTION_MOVE) {
        if (mExtensionKeyboardAreaEntranceTime <= 0)
            mExtensionKeyboardAreaEntranceTime = SystemClock.uptimeMillis();

        if (SystemClock.uptimeMillis()
                - mExtensionKeyboardAreaEntranceTime > DELAY_BEFORE_POPPING_UP_EXTENSION_KBD) {
            KeyboardExtension extKbd = ((ExternalAnyKeyboard) getKeyboard()).getExtensionLayout();
            if (extKbd == null || extKbd.getKeyboardResId() == AddOn.INVALID_RES_ID) {
                Logger.i(TAG, "No extension keyboard");
                return super.onTouchEvent(me);
            } else {
                // telling the main keyboard that the last touch was
                // canceled
                MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(),
                        MotionEvent.ACTION_CANCEL, me.getX(), me.getY(), 0);
                super.onTouchEvent(cancel);
                cancel.recycle();

                mExtensionVisible = true;
                dismissAllKeyPreviews();
                if (mExtensionKey == null) {
                    mExtensionKey = new AnyKey(new Keyboard.Row(getKeyboard()), getThemedKeyboardDimens());
                    mExtensionKey.edgeFlags = 0;
                    mExtensionKey.height = 1;
                    mExtensionKey.width = 1;
                    mExtensionKey.popupResId = extKbd.getKeyboardResId();
                    mExtensionKey.externalResourcePopupLayout = mExtensionKey.popupResId != 0;
                    mExtensionKey.x = getWidth() / 2;
                    mExtensionKey.y = mExtensionKeyboardPopupOffset;
                }
                // so the popup will be right above your finger.
                mExtensionKey.x = (int) me.getX();

                onLongPress(extKbd, mExtensionKey, AnyApplication.getConfig().isStickyExtensionKeyboard(),
                        getPointerTracker(me));
                // it is an extension..
                getMiniKeyboard().setPreviewEnabled(true);
                return true;
            }
        } else {
            return super.onTouchEvent(me);
        }
    } else if (mExtensionVisible && me.getY() > mExtensionKeyboardYDismissPoint) {
        // closing the popup
        dismissPopupKeyboard();
        return true;
    } else {
        return super.onTouchEvent(me);
    }
}

From source file:com.github.pedrovgs.DraggableView.java

/**
 * Clone given motion event and set specified action. This method is useful, when we want to
 * cancel event propagation in child views by sending event with {@link MotionEvent#ACTION_CANCEL} action.
 * @param event event to clone/*from  w w  w. j  ava  2  s .  c  o  m*/
 * @param action new action
 * @return cloned motion event
 */
private MotionEvent cloneMotionEventWithAction(MotionEvent event, int action) {
    return MotionEvent.obtain(event.getDownTime(), event.getEventTime(), action, event.getX(), event.getY(),
            event.getMetaState());
}

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

@Override
public boolean onTouchEvent(@NonNull MotionEvent me) {
    if (getKeyboard() == null)//I mean, if there isn't any keyboard I'm handling, what's the point?
        return false;

    if (areTouchesDisabled(me)) {
        return super.onTouchEvent(me);
    }/*  w  w  w . j a va2  s. c  o  m*/

    final int action = MotionEventCompat.getActionMasked(me);

    // Gesture detector must be enabled only when mini-keyboard is not
    // on the screen.
    if (!mMiniKeyboardPopup.isShowing() && mGestureDetector != null && mGestureDetector.onTouchEvent(me)) {
        Logger.d(TAG, "Gesture detected!");
        mKeyPressTimingHandler.cancelAllMessages();
        dismissAllKeyPreviews();
        return true;
    }

    if (action == MotionEvent.ACTION_DOWN) {
        mFirstTouchPoint.x = (int) me.getX();
        mFirstTouchPoint.y = (int) me.getY();
        mIsFirstDownEventInsideSpaceBar = mSpaceBarKey != null
                && mSpaceBarKey.isInside(mFirstTouchPoint.x, mFirstTouchPoint.y);
    }
    // If the motion event is above the keyboard and it's a MOVE event
    // coming even before the first MOVE event into the extension area
    if (!mIsFirstDownEventInsideSpaceBar && me.getY() < mExtensionKeyboardYActivationPoint
            && !mMiniKeyboardPopup.isShowing() && !mExtensionVisible && action == MotionEvent.ACTION_MOVE) {
        if (mExtensionKeyboardAreaEntranceTime <= 0)
            mExtensionKeyboardAreaEntranceTime = SystemClock.uptimeMillis();

        if (SystemClock.uptimeMillis()
                - mExtensionKeyboardAreaEntranceTime > DELAY_BEFORE_POPPING_UP_EXTENSION_KBD) {
            KeyboardExtension extKbd = ((ExternalAnyKeyboard) getKeyboard()).getExtensionLayout();
            if (extKbd == null || extKbd.getKeyboardResId() == AddOn.INVALID_RES_ID) {
                Logger.i(TAG, "No extension keyboard");
                return super.onTouchEvent(me);
            } else {
                // telling the main keyboard that the last touch was
                // canceled
                MotionEvent cancel = MotionEvent.obtain(me.getDownTime(), me.getEventTime(),
                        MotionEvent.ACTION_CANCEL, me.getX(), me.getY(), 0);
                super.onTouchEvent(cancel);
                cancel.recycle();

                mExtensionVisible = true;
                dismissAllKeyPreviews();
                if (mExtensionKey == null) {
                    mExtensionKey = new AnyKey(new Row(getKeyboard()), getThemedKeyboardDimens());
                    mExtensionKey.edgeFlags = 0;
                    mExtensionKey.height = 1;
                    mExtensionKey.width = 1;
                    mExtensionKey.popupResId = extKbd.getKeyboardResId();
                    mExtensionKey.externalResourcePopupLayout = mExtensionKey.popupResId != 0;
                    mExtensionKey.x = getWidth() / 2;
                    mExtensionKey.y = mExtensionKeyboardPopupOffset;
                }
                // so the popup will be right above your finger.
                mExtensionKey.x = (int) me.getX();

                onLongPress(extKbd, mExtensionKey, AnyApplication.getConfig().isStickyExtensionKeyboard(),
                        getPointerTracker(me));
                // it is an extension..
                getMiniKeyboard().setPreviewEnabled(true);
                return true;
            }
        } else {
            return super.onTouchEvent(me);
        }
    } else if (mExtensionVisible && me.getY() > mExtensionKeyboardYDismissPoint) {
        // closing the popup
        dismissPopupKeyboard();
        return true;
    } else {
        return super.onTouchEvent(me);
    }
}

From source file:io.selendroid.server.model.AndroidNativeElement.java

private void clickOnScreen(float x, float y) {
    SelendroidLogger.debug(String.format("Clicking at position [%f, %f]", x, y));
    final ServerInstrumentation inst = ServerInstrumentation.getInstance();
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    final MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, x, y, 0);
    final MotionEvent event2 = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);

    try {//w  w  w .  j a v  a2s  .c o m
        inst.sendPointerSync(event);
        inst.sendPointerSync(event2);
        try {
            Thread.sleep(300);
        } catch (InterruptedException ignored) {
        }
    } catch (SecurityException e) {
        SelendroidLogger.error("error while clicking element", e);
    }
}

From source file:com.jinzht.pro.view.RecyclerViewHeader.java

@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    if (mRecyclerWantsTouchEvent) {
        int scrollDiff = mCurrentScroll - mDownScroll;
        MotionEvent recyclerEvent = MotionEvent.obtain(event.getDownTime(), event.getEventTime(),
                event.getAction(), event.getX(), event.getY() - scrollDiff, event.getMetaState());
        mRecycler.onTouchEvent(recyclerEvent);
        return false;
    }//w w w .ja  va 2 s  .  co m
    return super.onTouchEvent(event);
}

From source file:com.malinskiy.superrecyclerview.SwipeDismissRecyclerViewTouchListener.java

private void performDismiss(final View dismissView, final int dismissPosition) {
    // Animate the dismissed list item to zero-height and fire the dismiss callback when
    // all dismissed list item animations have completed. This triggers layout on each animation
    // frame; in the future we may want to do something smarter and more performant.

    final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
    final int originalHeight = dismissView.getHeight();

    ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);

    animator.addListener(new AnimatorListenerAdapter() {
        @Override//from w  ww  . j a  v  a 2s.c  o  m
        public void onAnimationEnd(Animator animation) {
            --mDismissAnimationRefCount;
            if (mDismissAnimationRefCount == 0) {
                // No active animations, process all pending dismisses.
                // Sort by descending position
                Collections.sort(mPendingDismisses);

                int[] dismissPositions = new int[mPendingDismisses.size()];
                for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
                    dismissPositions[i] = mPendingDismisses.get(i).position;
                }
                mCallbacks.onDismiss(mRecyclerView, dismissPositions);

                // Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
                // animation with a stale position
                mDownPosition = INVALID_POSITION;

                ViewGroup.LayoutParams lp;
                for (PendingDismissData pendingDismiss : mPendingDismisses) {
                    // Reset view presentation
                    setAlpha(pendingDismiss.view, 1f);
                    setTranslationX(pendingDismiss.view, 0);
                    lp = pendingDismiss.view.getLayoutParams();
                    lp.height = originalHeight;
                    pendingDismiss.view.setLayoutParams(lp);
                }

                // Send a cancel event
                long time = SystemClock.uptimeMillis();
                MotionEvent cancelEvent = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0, 0, 0);
                mRecyclerView.dispatchTouchEvent(cancelEvent);

                mPendingDismisses.clear();
            }
        }
    });

    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            lp.height = (Integer) valueAnimator.getAnimatedValue();
            dismissView.setLayoutParams(lp);
        }
    });

    mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
    animator.start();
}

From source file:br.com.devmix.baseapp.listener.OnSwipeableRecyclerViewTouchListener.java

private void performDismiss(final View dismissView, final int dismissPosition) {
    // Animate the dismissed list item to zero-height and fire the dismiss callback when
    // all dismissed list item animations have completed. This triggers layout on each animation
    // frame; in the future we may want to do something smarter and more performant.

    final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
    final int originalLayoutParamsHeight = lp.height;
    final int originalHeight = dismissView.getHeight();

    ValueAnimatorCompat animatorCompat = AnimatorCompatHelper.emptyValueAnimator();
    animatorCompat.setDuration(mAnimationTime);
    animatorCompat.addListener(new AnimatorListenerCompat() {
        @Override/*  w  w  w  . j av a 2  s.com*/
        public void onAnimationStart(ValueAnimatorCompat animation) {
        }

        @Override
        public void onAnimationEnd(ValueAnimatorCompat animation) {
            --mDismissAnimationRefCount;
            if (mDismissAnimationRefCount == 0) {
                // No active animations, process all pending dismisses.
                // Sort by descending position
                Collections.sort(mPendingDismisses);

                int[] dismissPositions = new int[mPendingDismisses.size()];
                for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
                    dismissPositions[i] = mPendingDismisses.get(i).position;
                }

                if (mFinalDelta > 0) {
                    mSwipeListener.onDismissedBySwipeRight(mRecyclerView, dismissPositions);
                } else {
                    mSwipeListener.onDismissedBySwipeLeft(mRecyclerView, dismissPositions);
                }

                // Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
                // animation with a stale position
                mDownPosition = ListView.INVALID_POSITION;

                ViewGroup.LayoutParams lp;
                for (PendingDismissData pendingDismiss : mPendingDismisses) {
                    // Reset view presentation
                    ViewCompat.setAlpha(pendingDismiss.view, mAlpha);
                    ViewCompat.setTranslationX(pendingDismiss.view, 0);

                    lp = pendingDismiss.view.getLayoutParams();
                    lp.height = originalLayoutParamsHeight;

                    pendingDismiss.view.setLayoutParams(lp);
                }

                // Send a cancel event
                long time = SystemClock.uptimeMillis();
                MotionEvent cancelEvent = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0, 0, 0);
                mRecyclerView.dispatchTouchEvent(cancelEvent);

                mPendingDismisses.clear();
                mAnimatingPosition = ListView.INVALID_POSITION;
            }
        }

        @Override
        public void onAnimationCancel(ValueAnimatorCompat animation) {
        }

        @Override
        public void onAnimationRepeat(ValueAnimatorCompat animation) {
        }
    });
    animatorCompat.addUpdateListener(new AnimatorUpdateListenerCompat() {
        @Override
        public void onAnimationUpdate(ValueAnimatorCompat animation) {
            float fraction = animation.getAnimatedFraction();
            lp.height = (int) (originalHeight * (1 - fraction));
            dismissView.setLayoutParams(lp);
        }
    });

    mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
    animatorCompat.start();
}