Example usage for android.view MotionEvent getEventTime

List of usage examples for android.view MotionEvent getEventTime

Introduction

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

Prototype

@Override
public final long getEventTime() 

Source Link

Document

Retrieve the time this event occurred, in the android.os.SystemClock#uptimeMillis time base.

Usage

From source file:org.deviceconnect.android.deviceplugin.theta.fragment.ThetaShootingFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.theta_shooting_mode, null);
    ThetaDeviceApplication app = (ThetaDeviceApplication) getActivity().getApplication();
    ThetaDeviceManager deviceMgr = app.getDeviceManager();
    deviceMgr.registerDeviceEventListener(this);
    mDevice = deviceMgr.getConnectedDevice();
    if (mDevice == null) {
        ThetaDialogFragment.showAlert(getActivity(), getString(R.string.theta_ssid_prefix),
                getString(R.string.theta_error_disconnect_dialog_message),
                new DialogInterface.OnClickListener() {
                    @Override/* w  ww  .  j a va  2  s. co  m*/
                    public void onClick(DialogInterface dialogInterface, int i) {
                        getActivity().finish();
                    }
                });

        return rootView;
    }
    mShootingTime = (TextView) rootView.findViewById(R.id.shooting_time);
    mLiveView = (SphericalImageLiveView) rootView.findViewById(R.id.shooting_preview);
    mApi = app.getSphericalViewApi();
    mLiveView.setViewApi(mApi);
    mLiveView.setDeviceManager(deviceMgr);
    initShootingLayouts(rootView);
    mShootingMode = (Spinner) rootView.findViewById(R.id.theta_shooting_mode);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.theta_shooting_mode_adapter,
            getResources().getStringArray(R.array.theta_shooting_mode));

    mShootingMode.setAdapter(adapter);
    setRetainInstance(true);
    if (mShootingTasker == null) {
        mShootingTasker = new DownloadThetaDataTask();
        ShootingModeGetTask shootingGetTask = new ShootingModeGetTask();
        mShootingTasker.execute(shootingGetTask);
    }
    mLiveView.setOnTouchListener(new View.OnTouchListener() {

        private boolean mIsEnabledLongTouch = true;

        @Override
        public boolean onTouch(final View view, final MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                mIsEnabledLongTouch = true;
                return true;
            }
            if (motionEvent.getPointerCount() == 1) {
                if (mIsEnabledLongTouch && motionEvent.getEventTime() - motionEvent.getDownTime() >= 300) {
                    mLiveView.resetCameraDirection();
                }
            } else {
                mIsEnabledLongTouch = false;
                mScaleDetector.onTouchEvent(motionEvent);
            }
            return true;
        }
    });
    mScaleDetector = new ScaleGestureDetector(getActivity(),
            new ScaleGestureDetector.SimpleOnScaleGestureListener() {
                @Override
                public boolean onScale(final ScaleGestureDetector detector) {
                    mScaleFactor /= detector.getScaleFactor();
                    double scale = mScaleFactor;
                    if (scale > MAX_FOV) {
                        scale = MAX_FOV;
                        mScaleFactor = MAX_FOV;
                    }
                    if (scale < MIN_FOV) {
                        scale = MIN_FOV;
                        mScaleFactor = MIN_FOV;
                    }
                    mLiveView.setFOV(scale);

                    return true;
                }
            });
    rotateShootingButton(getActivity().getResources().getConfiguration());
    return rootView;
}

From source file:de.lmu.ifi.medien.probui.system.ProbUIManager.java

public void manageHelper(MotionEvent ev) throws WrongObservationDelegationException {

    this.currentTouchObservations.clear();

    int action = MotionEventCompat.getActionMasked(ev);
    int index = MotionEventCompat.getActionIndex(ev);
    int pointerID = ev.getPointerId(index);

    int type = -1;
    switch (action) {
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_POINTER_DOWN:
        type = ProbObservationTouch.TYPE_TOUCH_DOWN;
        break;//  ww  w  . ja v  a  2  s .  c  o  m
    case MotionEvent.ACTION_MOVE:
        type = ProbObservationTouch.TYPE_TOUCH_MOVE;
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_POINTER_UP:
        type = ProbObservationTouch.TYPE_TOUCH_UP;
        break;
    default:
        type = -1;
        break;
    }

    long timestamp = ev.getEventTime();

    ProbObservationTouch observation = ProbObservationFactory.createTouchObservation(ev.getX(index),
            ev.getY(index), ev.getX(index) * 1.0 / container.getWidth(),
            ev.getY(index) * 1.0 / container.getHeight(), ev.getOrientation(index),
            ev.getTouchMinor(index) * 1.0 / container.getWidth(),
            ev.getTouchMajor(index) * 1.0 / container.getHeight(), ev.getPressure(index), type, pointerID,
            timestamp);
    this.currentTouchObservations.add(observation);

    // Since move is always associated with the first pointer,
    // we need to manually duplicate it for the second one
    // (TODO: and for further pointers, if we change it to more than 2):
    if (ev.getPointerCount() == 2 && type == ProbObservationTouch.TYPE_TOUCH_MOVE) {
        ProbObservationTouch observation2 = ProbObservationFactory.createTouchObservation(ev.getX(index),
                ev.getY(index), ev.getX(1) * 1.0 / container.getWidth(),
                ev.getY(1) * 1.0 / container.getHeight(), ev.getOrientation(1),
                ev.getToolMinor(1) * 1.0 / container.getWidth(),
                ev.getToolMajor(1) * 1.0 / container.getHeight(), ev.getPressure(1), type, ev.getPointerId(1),
                timestamp);
        this.currentTouchObservations.add(observation2);
    }

    //Log.d("MULTITOUCH", "type: " + type + ", index: " + pointerID + ", size: " + ev.getTouchMajor(index) * 1.0 / container.getHeight());

    // Distribute touch observation to the cores of all probInteractors
    // (for reasoning by these interactor cores!, not for visual feedback etc. - that comes below: interactor.onTouchDown etc.)
    boolean passedOn = false;
    for (ProbInteractor interactor : this.probInteractors) {

        for (int i = 0; i < this.currentTouchObservations.size(); i++) {
            ProbObservationTouch obs = this.currentTouchObservations.get(i);
            if (obs == null)
                continue;
            if (obs.getNominalFeatures()[0] != ProbObservationTouch.TYPE_TOUCH_MOVE
                    || this.currentTouchObservations.size() != this.previousTouchObservations.size()) {
                interactor.getCore().onTouchObservation(obs);
                passedOn = true;
            } else { // This code filters out move events that moved very little (potentially improves performance):
                double[] obsXY = this.currentTouchObservations.get(i).getRealFeatures();
                double[] obsPrevXY = this.previousTouchObservations.get(i).getRealFeatures();
                double dx = obsXY[0] - obsPrevXY[0];
                double dy = obsXY[1] - obsPrevXY[1];
                double dist = Math.sqrt(dx * dx + dy * dy);
                if (dist > 0.0125) { // TODO: movement threshold currently hardcoded: 0.0125
                    interactor.getCore().onTouchObservation(obs);
                    passedOn = true;
                } else {
                }
            }
        }

    }

    if (passedOn) {
        this.previousTouchObservations.clear();
        this.previousTouchObservations.addAll(this.currentTouchObservations);
    }

    // Forward the touch observation for probInteractors
    // to react (e.g. visual feedback, triggering actions, nothing to do with the mediation):
    for (ProbInteractor interactor : this.probInteractors) {
        for (ProbObservationTouch obs : this.currentTouchObservations) {
            if (obs != null) {
                switch (obs.getNominalFeatures()[0]) {

                case ProbObservationTouch.TYPE_TOUCH_DOWN:
                    interactor.onTouchDown(obs);
                    break;

                case ProbObservationTouch.TYPE_TOUCH_MOVE:
                    interactor.onTouchMove(obs);
                    break;

                case ProbObservationTouch.TYPE_TOUCH_UP:
                    interactor.onTouchUp(obs, ev.getPointerCount() - 1);
                    break;
                default:
                    break;
                }
            }
        }
    }

    // If no element is determined yet (i.e. no decision yet), update the reasoning process.
    if (!isOneDetermined() && passedOn) {
        this.mediator.mediate(false);
    }

    // Post mediation: Forward the touch observation again
    // to the post-mediation versions of the onTouch... methods
    for (ProbInteractor interactor : this.probInteractors) {
        for (ProbObservationTouch obs : this.currentTouchObservations) {
            if (obs != null) {
                switch (obs.getNominalFeatures()[0]) {

                case ProbObservationTouch.TYPE_TOUCH_DOWN:
                    interactor.onTouchDownPost(obs);
                    break;

                case ProbObservationTouch.TYPE_TOUCH_MOVE:
                    interactor.onTouchMovePost(obs);
                    break;

                case ProbObservationTouch.TYPE_TOUCH_UP:
                    interactor.onTouchUpPost(obs, ev.getPointerCount() - 1);
                    break;
                default:
                    break;
                }
            }
        }
    }

    // Pass on to other GUI elements:
    if (!isOneDetermined()) {
        for (View view : this.nonProbInteractors) {
            if (view.isFocusable() && view.isEnabled())
                view.onTouchEvent(ev);
        }
    }
}

From source file:de.dmxcontrol.activity.ControlActivity.java

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (!isPointInsideView(event.getX(), event.getY(),
            fManager.findFragmentById(R.id.action_fragment).getView())) {
        if (event.getPointerCount() == 2 && oldState == ActionSelectorFragment.STATE_OPTIC_PANEL) {
            return super.dispatchTouchEvent(event);
        } else {//from  w w  w. j a va  2 s .  co  m

            gestureDetector.onTouchEvent(event);
        }
        switch (oldState) {
        case ActionSelectorFragment.STATE_INTENSITY_PANEL:
        case ActionSelectorFragment.STATE_COLOR_PANEL:
        case ActionSelectorFragment.STATE_PANTILT_PANEL:
            if (!(event.getAction() == MotionEvent.ACTION_MOVE) || event.getEventTime()
                    - event.getDownTime() > this.getResources().getInteger(R.integer.touch_gesture_delay)) {
                return super.dispatchTouchEvent(event);
            }
            return false;
        default:
            return super.dispatchTouchEvent(event);
        }
    }
    return super.dispatchTouchEvent(event);
}

From source file:it.sephiroth.android.library.imagezoom.ScaleGestureDetector.java

private void setContext(final MotionEvent curr) {
    if (mCurrEvent != null) {
        mCurrEvent.recycle();//  w  w  w . ja  v  a2s.  c om
    }
    mCurrEvent = MotionEvent.obtain(curr);

    mCurrLen = -1;
    mPrevLen = -1;
    mScaleFactor = -1;

    final MotionEvent prev = mPrevEvent;

    final float px0 = prev.getX(0);
    final float py0 = prev.getY(0);
    final float px1 = prev.getX(1);
    final float py1 = prev.getY(1);
    final float cx0 = curr.getX(0);
    final float cy0 = curr.getY(0);
    final float cx1 = curr.getX(1);
    final float cy1 = curr.getY(1);

    final float pvx = px1 - px0;
    final float pvy = py1 - py0;
    final float cvx = cx1 - cx0;
    final float cvy = cy1 - cy0;
    mPrevFingerDiffX = pvx;
    mPrevFingerDiffY = pvy;
    mCurrFingerDiffX = cvx;
    mCurrFingerDiffY = cvy;

    mFocusX = cx0 + cvx * 0.5f;
    mFocusY = cy0 + cvy * 0.5f;
    mTimeDelta = curr.getEventTime() - prev.getEventTime();
    mCurrPressure = curr.getPressure(0) + curr.getPressure(1);
    mPrevPressure = prev.getPressure(0) + prev.getPressure(1);
}

From source file:org.telegram.ui.Components.NumberPicker.java

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    if (!isEnabled()) {
        return false;
    }/*from w  ww  .  jav a  2 s . co  m*/
    final int action = event.getActionMasked();
    switch (action) {
    case MotionEvent.ACTION_DOWN: {
        removeAllCallbacks();
        mInputText.setVisibility(View.INVISIBLE);
        mLastDownOrMoveEventY = mLastDownEventY = event.getY();
        mLastDownEventTime = event.getEventTime();
        mIngonreMoveEvents = false;
        if (mLastDownEventY < mTopSelectionDividerTop) {
            if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
                mPressedStateHelper.buttonPressDelayed(PressedStateHelper.BUTTON_DECREMENT);
            }
        } else if (mLastDownEventY > mBottomSelectionDividerBottom) {
            if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
                mPressedStateHelper.buttonPressDelayed(PressedStateHelper.BUTTON_INCREMENT);
            }
        }
        getParent().requestDisallowInterceptTouchEvent(true);
        if (!mFlingScroller.isFinished()) {
            mFlingScroller.forceFinished(true);
            mAdjustScroller.forceFinished(true);
            onScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
        } else if (!mAdjustScroller.isFinished()) {
            mFlingScroller.forceFinished(true);
            mAdjustScroller.forceFinished(true);
        } else if (mLastDownEventY < mTopSelectionDividerTop) {
            postChangeCurrentByOneFromLongPress(false, ViewConfiguration.getLongPressTimeout());
        } else if (mLastDownEventY > mBottomSelectionDividerBottom) {
            postChangeCurrentByOneFromLongPress(true, ViewConfiguration.getLongPressTimeout());
        }
        return true;
    }
    }
    return false;
}

From source file:com.fishstix.dosboxfree.DBGLSurfaceView.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override/*w ww .  j  a va 2  s.  c  om*/
public boolean onGenericMotionEvent(MotionEvent event) {
    if (event.getEventTime() + EVENT_THRESHOLD_DECAY < SystemClock.uptimeMillis()) {
        //Log.i("DosBoxTurbo","eventtime: "+event.getEventTime() + " systemtime: "+SystemClock.uptimeMillis());
        return true; // get rid of old events
    }
    final int pointerIndex = MotionEventCompat.getActionIndex(event);
    final int pointerId = MotionEventCompat.getPointerId(event, pointerIndex);

    if ((MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_MOVE) && ((mWrap.getSource(event)
            & TouchEventWrapper.SOURCE_CLASS_MASK) == TouchEventWrapper.SOURCE_CLASS_JOYSTICK)) {
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) && (mAnalogStickPref < 3)) {
            // use new 3.1 API to handle joystick movements
            int historySize = event.getHistorySize();
            for (int i = 0; i < historySize; i++) {
                processJoystickInput(event, i);
            }

            processJoystickInput(event, -1);
            return true;
        } else {
            // use older 2.2+ API to handle joystick movements
            if (mInputMode == INPUT_MODE_REAL_JOYSTICK) {
                x[pointerId] = mWrap.getX(event, pointerId);
                y[pointerId] = mWrap.getY(event, pointerId);
                DosBoxControl.nativeJoystick((int) ((x[pointerId] * 256f) + mJoyCenterX),
                        (int) ((y[pointerId] * 256f) + mJoyCenterY), ACTION_MOVE, -1);
                return true;
            }
        }
    } else if ((MotionEventCompat.getActionMasked(event) == MotionEventCompat.ACTION_HOVER_MOVE)
            && ((mWrap.getSource(event)
                    & TouchEventWrapper.SOURCE_CLASS_MASK) == TouchEventWrapper.SOURCE_CLASS_POINTER)) {
        if (mInputMode == INPUT_MODE_REAL_MOUSE) {
            x_last[pointerId] = x[pointerId];
            y_last[pointerId] = y[pointerId];
            x[pointerId] = mWrap.getX(event, pointerId);
            y[pointerId] = mWrap.getY(event, pointerId);
            if (mAbsolute) {
                DosBoxControl.nativeMouseWarp(x[pointerId], y[pointerId], mRenderer.x, mRenderer.y,
                        mRenderer.width, mRenderer.height);
            } else {
                DosBoxControl.nativeMouse((int) (x[pointerId] * mMouseSensitivityX),
                        (int) (y[pointerId] * mMouseSensitivityY),
                        (int) (x_last[pointerId] * mMouseSensitivityX),
                        (int) (y_last[pointerId] * mMouseSensitivityY), 2, -1);
            }

            int buttonState = mWrap.getButtonState(event);
            if (((buttonState & TouchEventWrapper.BUTTON_SECONDARY) != 0) && !mSPenButton) {
                // Handle Samsung SPen Button (RMB) - DOWN
                DosBoxControl.nativeMouse(0, 0, 0, 0, ACTION_DOWN, BTN_B);
                mSPenButton = true;
            } else if (((buttonState & TouchEventWrapper.BUTTON_SECONDARY) == 0) && mSPenButton) {
                // Handle Samsung SPen Button (RMB) - UP
                DosBoxControl.nativeMouse(0, 0, 0, 0, ACTION_UP, BTN_B);
                mSPenButton = false;
            }

            if (mDebug)
                Log.d("DosBoxTurbo", "onGenericMotionEvent() INPUT_MODE_REAL_MOUSE x: " + x[pointerId] + "  y: "
                        + y[pointerId] + "  |  xL: " + x_last[pointerId] + "  yL: " + y_last[pointerId]);
            try {
                if (!mInputLowLatency)
                    Thread.sleep(95);
                else
                    Thread.sleep(65);
            } catch (InterruptedException e) {
            }
            return true;
        }
    } else if (MotionEventCompat.getActionMasked(event) == MotionEventCompat.ACTION_HOVER_EXIT) {
        if (mInputMode == INPUT_MODE_REAL_MOUSE) {
            // hover exit
            int buttonState = mWrap.getButtonState(event);
            if (((buttonState & TouchEventWrapper.BUTTON_SECONDARY) == 0) && mSPenButton) {
                // Handle Samsung SPen Button (RMB) - UP
                DosBoxControl.nativeMouse(0, 0, 0, 0, ACTION_UP, BTN_B);
                mSPenButton = false;
                return true;
            }
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
        return super.onGenericMotionEvent(event);
    } else {
        return false;
    }
}

From source file:com.mylikes.likes.etchasketch.Slate.java

@SuppressLint("NewApi")
@Override/*  w ww .j a v  a  2  s. c o m*/
public boolean onTouchEvent(MotionEvent event) {
    final int action = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? event.getActionMasked()
            : event.getAction();
    int N = event.getHistorySize();
    int P = event.getPointerCount();
    long time = event.getEventTime();

    mEmpty = false;

    // starting a new touch? commit the previous state of the canvas
    if (action == MotionEvent.ACTION_DOWN) {
        commitStroke();
    }

    if (mZoomMode) {
        return false;
    }

    int pointerIndex = MotionEventCompat.getActionIndex(event);
    int pointerId = event.getPointerId(pointerIndex);
    if (moveMode) {
        if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) {
            if (firstFinger != null) {
                MotionEvent.PointerCoords coords1 = new MotionEvent.PointerCoords();
                event.getPointerCoords(0, coords1);
                Log.d(TAG, "coords1: " + coords1.x + " " + coords1.y);
                MotionEvent.PointerCoords coords2 = new MotionEvent.PointerCoords();
                event.getPointerCoords(1, coords2);
                firstFinger.set(coords1.x, coords1.y);
                secondFinger = new PointF(coords2.x, coords2.y);
            } else {
                touchStartTime = System.currentTimeMillis();
                moveDrawingStartX = event.getX();
                moveDrawingStartY = event.getY();
                int i = 0;
                moveDrawingIndex = -1;
                resizeDrawingIndex = -1;
                resizeDrawingCorner = null;
                if (selectedDrawing != null) {
                    moveDrawingIndex = 0;
                }
                if (i >= overlays.size()) {
                    return true;
                }
                Log.d(TAG, "Start dragging overlay");
                firstFinger = new PointF(event.getX(), event.getY());
            }
            return true;
        } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
            if (secondFinger != null) {
                secondFinger = null;
                MotionEvent.PointerCoords coords1 = new MotionEvent.PointerCoords();
                event.getPointerCoords(0, coords1);
                moveDrawingStartX = coords1.x;
                moveDrawingStartY = coords1.y;
                return true;
            }
            if (firstFinger != null) {
                firstFinger = null;
            }
            if (moveDrawingIndex == -1 && resizeDrawingIndex == -1
                    && System.currentTimeMillis() - touchStartTime < 400
                    && Math.abs(event.getX() - moveDrawingStartX)
                            + Math.abs(event.getY() - moveDrawingStartY) < 8) {
                if (resizeDrawingCorner != null && selectedDrawing != null) {
                    if (resizeDrawingCorner == "tl" && selectedDrawing instanceof TextDrawing) {
                        //promptForText((TextDrawing)selectedDrawing);
                    } else if (resizeDrawingCorner == "tr") {
                        //maybeRemoveDrawing(selectedDrawing);
                    }
                } else {
                    //promptForText((int) event.getX(), (int) event.getY());
                }
            }
            moveDrawingIndex = -1;
            Log.d(TAG, "Stop dragging overlay");
            // TODO: add to undo stack
            return true;
        } else if (firstFinger != null && secondFinger != null && action == MotionEvent.ACTION_MOVE) {
            MotionEvent.PointerCoords coords1 = new MotionEvent.PointerCoords();
            event.getPointerCoords(0, coords1);
            Log.d(TAG, "coords1: " + coords1.x + " " + coords1.y);
            MotionEvent.PointerCoords coords2 = new MotionEvent.PointerCoords();
            event.getPointerCoords(1, coords2);
            Log.d(TAG, "coords2: " + coords2.x + " " + coords2.y);
            float xDist = firstFinger.x - secondFinger.x, yDist = firstFinger.y - secondFinger.y;
            float origAngle = (float) Math.atan2(yDist, xDist);
            if (origAngle < 0)
                origAngle += Math.PI * 2;
            float lastDistance = (float) Math.sqrt(xDist * xDist + yDist * yDist);

            xDist = coords2.x - coords1.x;
            yDist = coords2.y - coords1.y;
            float newDistance = (float) Math.sqrt(xDist * xDist + yDist * yDist);
            float newAngle = (float) Math.atan2(yDist, xDist);
            if (newAngle < 0)
                newAngle += Math.PI * 2;
            if (newAngle - origAngle > Math.PI / 2) {
                origAngle += Math.PI;
            } else if (origAngle - newAngle > Math.PI / 2) {
                newAngle += Math.PI;
            }

            firstFinger.set(coords1.x, coords1.y);
            secondFinger = new PointF(coords2.x, coords2.y);
            if (selectedDrawing != null) {
                selectedDrawing.resizeBy(newDistance / lastDistance);
                selectedDrawing.rotateBy(newAngle - origAngle);
                invalidate();
            }
        } else if (moveDrawingIndex >= 0 && moveDrawingIndex < overlays.size()
                && action == MotionEvent.ACTION_MOVE) {
            float x = event.getX();
            float y = event.getY();
            overlays.get(moveDrawingIndex).moveBy((int) ((x - moveDrawingStartX) * getDrawingDensity()),
                    (int) ((y - moveDrawingStartY) * getDrawingDensity()));
            // TODO: only invalidate relevant Rect
            invalidate();
            moveDrawingStartX = x;
            moveDrawingStartY = y;
            return true;
        } else if (resizeDrawingIndex >= 0 && resizeDrawingIndex < overlays.size()
                && action == MotionEvent.ACTION_MOVE) {
            float x = event.getX();
            float y = event.getY();
            overlays.get(resizeDrawingIndex).resizeCorner(resizeDrawingCorner, (int) (x - moveDrawingStartX),
                    (int) (y - moveDrawingStartY));
            // TODO: only invalidate relevant Rect
            invalidate();
            moveDrawingStartX = x;
            moveDrawingStartY = y;
            return true;
        }
        return false;
    }

    if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN
            || action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
        int j = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? event.getActionIndex() : 0;

        mTmpSpot.update(event.getX(j), event.getY(j), event.getSize(j), event.getPressure(j) + event.getSize(j),
                time, getToolTypeCompat(event, j));
        mStrokes[event.getPointerId(j)].add(mTmpSpot);
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
            mStrokes[event.getPointerId(j)].finish(time);
        }
    } else if (action == MotionEvent.ACTION_MOVE) {
        if (dbgX >= 0) {
            dbgRect.set(dbgX - 1, dbgY - 1, dbgX + 1, dbgY + 1);
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < P; j++) {
                mTmpSpot.update(event.getHistoricalX(j, i), event.getHistoricalY(j, i),
                        event.getHistoricalSize(j, i),
                        event.getHistoricalPressure(j, i) + event.getHistoricalSize(j, i),
                        event.getHistoricalEventTime(i), getToolTypeCompat(event, j));
                if ((mDebugFlags & FLAG_DEBUG_STROKES) != 0) {
                    if (dbgX >= 0) {
                        //mTiledCanvas.drawLine(dbgX, dbgY, mTmpSpot.x, mTmpSpot.y, mDebugPaints[3]);
                    }
                    dbgX = mTmpSpot.x;
                    dbgY = mTmpSpot.y;
                    dbgRect.union(dbgX - 1, dbgY - 1, dbgX + 1, dbgY + 1);
                }
                mStrokes[event.getPointerId(j)].add(mTmpSpot);
            }
        }
        for (int j = 0; j < P; j++) {
            mTmpSpot.update(event.getX(j), event.getY(j), event.getSize(j),
                    event.getPressure(j) + event.getSize(j), time, getToolTypeCompat(event, j));
            if ((mDebugFlags & FLAG_DEBUG_STROKES) != 0) {
                if (dbgX >= 0) {
                    //mTiledCanvas.drawLine(dbgX, dbgY, mTmpSpot.x, mTmpSpot.y, mDebugPaints[3]);
                }
                dbgX = mTmpSpot.x;
                dbgY = mTmpSpot.y;
                dbgRect.union(dbgX - 1, dbgY - 1, dbgX + 1, dbgY + 1);
            }
            mStrokes[event.getPointerId(j)].add(mTmpSpot);
        }

        if ((mDebugFlags & FLAG_DEBUG_STROKES) != 0) {
            Rect dirty = new Rect();
            dbgRect.roundOut(dirty);
            invalidate(dirty);
        }
    }

    if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
        for (int j = 0; j < P; j++) {
            mStrokes[event.getPointerId(j)].finish(time);
        }
        dbgX = dbgY = -1;
    }
    return true;
}

From source file:org.readium.sdk.android.biblemesh.WebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

    setContentView(R.layout.activity_web_view);

    final int abTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
    findViewById(abTitleId).setOnClickListener(new View.OnClickListener() {

        @Override/* w  w w .  j  a va2 s. c  o m*/
        public void onClick(View v) {
            finish();
        }
    });

    mWebview = (WebView) findViewById(R.id.webview);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && 0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    mProgress = (ProgressBar) findViewById(R.id.progressBar);
    initWebView();

    final GestureDetector gestureDetector = new GestureDetector(this, new MyGestureListener());

    mWebview.setOnTouchListener(new View.OnTouchListener() {

        private final static long MAX_TOUCH_DURATION = 150;
        float lastEventX;
        float m_DownTime;

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastEventX = event.getX();
                m_DownTime = event.getEventTime(); //init time
                break;
            case MotionEvent.ACTION_MOVE: {
                float distanceX = lastEventX - event.getX();

                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();

                marginLayoutParams.leftMargin = marginLayoutParams.leftMargin - (int) distanceX;
                marginLayoutParams.rightMargin = -marginLayoutParams.leftMargin;// marginLayoutParams.rightMargin + (int) distanceX;

                mWebview.requestLayout();
            }
                break;
            case MotionEvent.ACTION_UP: {
                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();
                if (marginLayoutParams.leftMargin < 10 && marginLayoutParams.leftMargin > -10) {
                    Log.i("up", "small margin, open menu?");
                    if (event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION) {
                        Log.i("up", "quick");
                        showActionBar(null);
                    } else {
                        Log.i("up", "too long");
                    }
                }
            }
            case MotionEvent.ACTION_CANCEL: {
                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();

                //Log.i("snap", "snap width: "+mWebview.getWidth()+" left:" + marginLayoutParams.leftMargin + " raw:" + event.getRawX() + " " + event.getX());//+" "+e2.toString()+" "+e1.toString());
                //mWebview.getWidth()
                if (marginLayoutParams.leftMargin < -0.5 * mWebview.getWidth()) {
                    mReadiumJSApi.openPageRight();
                    mWebview.setAlpha(0.0f);
                } else if (marginLayoutParams.leftMargin > 0.5 * mWebview.getWidth()) {
                    mReadiumJSApi.openPageLeft();
                    mWebview.setAlpha(0.0f);
                } else {
                    snapBack();
                    //return true;
                }
            }
                break;
            }
            ;
            return gestureDetector.onTouchEvent(event);
        }
    });
    /*mWebview.setHapticFeedbackEnabled(false);*/

    Intent intent = getIntent();
    if (intent.getFlags() == Intent.FLAG_ACTIVITY_NEW_TASK) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mContainer = ContainerHolder.getInstance().get(extras.getLong(Constants.CONTAINER_ID));
            if (mContainer == null) {
                finish();
                return;
            }
            mPackage = mContainer.getDefaultPackage();

            String rootUrl = "http://" + EpubServer.HTTP_HOST + ":" + EpubServer.HTTP_PORT + "/";
            mPackage.setRootUrls(rootUrl, null);

            try {
                mOpenPageRequestData = OpenPageRequest
                        .fromJSON(extras.getString(Constants.OPEN_PAGE_REQUEST_DATA));
            } catch (JSONException e) {
                Log.e(TAG, "Constants.OPEN_PAGE_REQUEST_DATA must be a valid JSON object: " + e.getMessage(),
                        e);
            }
        }
    }

    // No need, EpubServer already launchers its own thread
    // new AsyncTask<Void, Void, Void>() {
    // @Override
    // protected Void doInBackground(Void... params) {
    // //xxx
    // return null;
    // }
    // }.execute();

    mServer = new EpubServer(EpubServer.HTTP_HOST, EpubServer.HTTP_PORT, mPackage, quiet, dataPreProcessor);
    mServer.startServer();

    // Load the page skeleton
    mWebview.loadUrl(READER_SKELETON);
    mViewerSettings = new ViewerSettings(ViewerSettings.SyntheticSpreadMode.SINGLE,
            ViewerSettings.ScrollMode.AUTO, 100, 20);

    mReadiumJSApi = new ReadiumJSApi(new ReadiumJSApi.JSLoader() {
        @Override
        public void loadJS(String javascript) {
            mWebview.loadUrl(javascript);
        }
    });

    /*Button back = (Button)findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
    onBackPressed();
    if(getActionBar.isShowing())
    {
       hideActionBar();
    }
    else
    {
       getActionBar.show();
       hideActionBar();
    }
       }
    });*/
    r = new Runnable() {
        @Override
        public void run() {
            getActionBar().hide();
            //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        }
    };
    hide2 = null;
    hideActionBar();
    //ActionBar actionBar = getActionBar();
    //actionBar.hide();
    //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}

From source file:io.authme.sdk.widget.LockPatternView.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!mInputEnabled || !isEnabled()) {
        return false;
    }/*from  w  w w. ja  v a 2s .  c om*/

    if (event.getAction() == MotionEvent.ACTION_MOVE && collectSensor == true) {
        float x = event.getX();
        float y = event.getY();
        RawXY xy = new RawXY(x, y, event.getEventTime());
        rawXYList.add(xy);
    }

    int index = event.getActionIndex();
    int pointerId = event.getPointerId(index);

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        handleActionDown(event);
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        } else {
            mVelocityTracker.clear();
        }
        mVelocityTracker.addMovement(event);
        return true;
    case MotionEvent.ACTION_UP:
        handleActionUp(event);
        return true;
    case MotionEvent.ACTION_MOVE:
        handleActionMove(event);
        mVelocityTracker.addMovement(event);
        mVelocityTracker.computeCurrentVelocity(1000);
        float x = VelocityTrackerCompat.getXVelocity(mVelocityTracker, pointerId);
        float y = VelocityTrackerCompat.getYVelocity(mVelocityTracker, pointerId);
        Velocity xy = new Velocity(x, y, event.getEventTime());
        velocityList.add(xy);
        return true;
    case MotionEvent.ACTION_CANCEL:
        /*
         * Original source check for mPatternInProgress == true first before
         * calling next three lines. But if we do that, there will be
         * nothing happened when the user taps at empty area and releases
         * the finger. We want the pattern to be reset and the message will
         * be updated after the user did that.
         */
        mVelocityTracker.recycle();
        mPatternInProgress = false;
        resetPattern();
        notifyPatternCleared();

        if (PROFILE_DRAWING) {
            if (mDrawingProfilingStarted) {
                Debug.stopMethodTracing();
                mDrawingProfilingStarted = false;
            }
        }
        return true;
    }
    return false;
}

From source file:com.timemachine.controller.ControllerActivity.java

private void setupUI() {
    // Set layout listener
    View controllerView = findViewById(R.id.controllerView);
    ViewTreeObserver vto = controllerView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override/*ww  w.j a  v a 2  s . c  om*/
        public void onGlobalLayout() {
            runOnUiThread(new Runnable() {
                public void run() {
                    locationSliderHeight = locationSlider.getHeight();
                    originLocationSliderContainerY = locationSliderContainer.getY();
                    originPlayPauseButtonY = playPause.getY();
                    minLocationSliderContainerY = originLocationSliderContainerY;
                    maxLocationSliderContainerY = originLocationSliderContainerY + locationSliderHeight;
                    midLocationSliderContainerY = (minLocationSliderContainerY + maxLocationSliderContainerY)
                            / 2;
                }
            });
            System.out.println("locationSliderHeight: " + locationSliderHeight);
            System.out.println("locationSliderContainerY: " + originLocationSliderContainerY);
            locationSlider.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });

    // Connect to controller.html
    controllerURL = "http://" + ipText + ":8080/controller.html";
    locationSlider = (WebView) findViewById(R.id.webview);
    locationSliderContainer = (FrameLayout) findViewById(R.id.sliderContainer);
    locationSlider.setBackgroundColor(Color.TRANSPARENT);
    locationSlider.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    locationSlider.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            System.out.println("onReceivedError");
            showConnectDialog("Error while connecting to controller. Connect again.");
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (url.contains("thumbnail"))
                isMasterConnected = true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            isMasterConnectedTimerTask = null;
            isMasterConnectedTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (isMasterConnected == false)
                        showConnectDialog("Master is not loaded in the browser. Connect again.");
                }
            };
            isMasterConnectedTimer.schedule(isMasterConnectedTimerTask, 6000);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (url.contains(controllerURL)) {
                drag.setVisibility(View.VISIBLE);
                playPause.setVisibility(View.VISIBLE);
                loadPreferences();
            }
            super.onPageFinished(view, url);
        }
    });
    try {
        locationSlider.loadUrl(controllerURL);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Set JavaScript Interface
    locationSlider.addJavascriptInterface(this, "androidObject");
    WebSettings webSettings = locationSlider.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Set the play-pause button
    playPause = (ImageButton) findViewById(R.id.playPauseButton);
    playPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            socket.emit("handlePlayPauseServer");
        }
    });
    socket.emit("setControllerPlayButton");

    // Set the drag button
    drag = (ImageButton) findViewById(R.id.drag);
    drag.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                dragYDiffBetweenFingerAndSliderTop = locationSliderContainer.getY() - event.getRawY();
                dragYDiffBetweenFingerAndPlayPauseTop = playPause.getY() - event.getRawY();
            }
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                // Move the slider based on current finger location
                float newSliderY = event.getRawY() + dragYDiffBetweenFingerAndSliderTop;
                float newPlayPauseY = event.getRawY() + dragYDiffBetweenFingerAndPlayPauseTop;
                if (newSliderY > minLocationSliderContainerY && newSliderY < maxLocationSliderContainerY) {
                    locationSliderContainer.setY(newSliderY);
                    playPause.setY(newPlayPauseY);
                }
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (event.getEventTime() - event.getDownTime() <= tapTimeout) {
                    // Tap is detected, toggle the slider
                    System.out.println("onTap");
                    runOnUiThread(new Runnable() {
                        public void run() {
                            toggleSlider();
                        }
                    });
                } else {
                    // Not a tap gesture, slide up or down based on the slider's current position
                    if (locationSliderContainer.getY() > midLocationSliderContainerY)
                        slideDown();
                    else
                        slideUp();
                }
            }
            return true;
        }
    });

    // Set the Google map
    setUpMapIfNeeded();
}