List of usage examples for android.view MotionEvent getActionIndex
public final int getActionIndex()
From source file:edu.uark.spARK.SwipeDismissListViewTouchListener.java
@Override public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mListView.getWidth(); }/* ww w. j a v a 2 s . c om*/ switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { mPaused = false; longClickActive = false; // if (mPaused) { // return false; // } // TODO: ensure this is a finger, and set a flag // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mListView.getChildCount(); int[] listViewCoords = new int[2]; mListView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; //ignore header views for (int i = 1; i < childCount; i++) { child = mListView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { mDownView = child; break; } } if (mDownView != null) { mDownView = mDownView.findViewById(R.id.table); mDownX = motionEvent.getRawX(); //TODO: really need to figure out why npe is happening here try { mDownPosition = mListView.getPositionForView(mDownView); } catch (NullPointerException npe) { //why does this keep happening? npe.printStackTrace(); } if (mCallbacks.canDismiss(mDownPosition)) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); } else { mDownView = null; } } view.onTouchEvent(motionEvent); return true; } case MotionEvent.ACTION_UP: { if (longClickActive) { RelativeLayout darkenTop = (RelativeLayout) mListView.getRootView() .findViewById(R.id.darkenScreenTop); ImageView darkenBottom = (ImageView) mListView.getRootView().findViewById(R.id.darkenScreenBottom); darkenTop.animate().alpha(0).setDuration(mAnimationTime).setListener(null); darkenBottom.animate().alpha(0).setDuration(mAnimationTime).setListener(null); if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss) { // dismiss dismiss(mDownView, mDownPosition, dismissRight); } else { // cancel mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; } break; } case MotionEvent.ACTION_CANCEL: { longClickActive = false; mPaused = false; RelativeLayout darkenTop = (RelativeLayout) mListView.getRootView().findViewById(R.id.darkenScreenTop); ImageView darkenBottom = (ImageView) mListView.getRootView().findViewById(R.id.darkenScreenBottom); darkenTop.animate().alpha(0).setDuration(mAnimationTime).setListener(null); darkenBottom.animate().alpha(0).setDuration(mAnimationTime).setListener(null); if (mVelocityTracker == null) { break; } if (mDownView != null) { // cancel mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } if (longClickActive) { mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; //the if statement is allowing the listview to scroll until a sufficient deltaX is made, while we want swiping immediately // if (Math.abs(deltaX) > mSlop) { mSwiping = true; mListView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) which is not what we want MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mListView.onTouchEvent(cancelEvent); cancelEvent.recycle(); // } if (mSwiping) { mDownView.setTranslationX(deltaX); //we don't want the alpha to change // mDownView.setAlpha(Math.max(0.15f, Math.min(1f, // 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } } break; } } return false; }
From source file:org.creativecommons.thelist.swipedismiss.SwipeDismissRecyclerViewTouchListener.java
@Override public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mRecyclerView.getWidth(); }/*from w ww.j a va 2 s. c om*/ switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mPaused) { return false; } // TODO: ensure this is a finger, and set a flag // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mRecyclerView.getChildCount(); int[] listViewCoords = new int[2]; mRecyclerView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; for (int i = 0; i < childCount; i++) { child = mRecyclerView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { mDownView = child; break; } } if (mDownView != null) { mDownX = motionEvent.getRawX(); mDownY = motionEvent.getRawY(); mDownPosition = mRecyclerView.getChildPosition(mDownView); if (mCallbacks.canDismiss(mDownPosition)) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); } else { mDownView = null; } } return false; } //OnTouch case MotionEvent.ACTION_CANCEL: { if (mVelocityTracker == null) { break; } if (mDownView != null && mSwiping) { // cancel //TODO: DOES THIS WORK animate(mDownView).translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; mRefreshLayout.setEnabled(true); break; } //ACTION_CANCEL case MotionEvent.ACTION_UP: { if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); // float velocityX = Math.abs(mVelocityTracker.getXVelocity()); // float velocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX && mSwiping) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss && mDownPosition != ListView.INVALID_POSITION) { // dismiss final View downView = mDownView; // mDownView gets null'd before animation ends final int downPosition = mDownPosition; ++mDismissAnimationRefCount; //TODO: add animation lock // synchronized (mAnimationLock){ // if(mAnimatedViews.contains(downView)){ // break; // } // ++mDismissAnimationRefCount; // mAnimatedViews.add(downView); // } animate(mDownView).translationX(dismissRight ? mViewWidth : -mViewWidth).alpha(0) .setDuration(mAnimationTime) .setListener(new com.nineoldandroids.animation.AnimatorListenerAdapter() { @Override public void onAnimationEnd(com.nineoldandroids.animation.Animator animation) { performDismiss(downView, downPosition); } }); } else { // cancel animate(mDownView).translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; mRefreshLayout.setEnabled(true); break; } //ACTION_UP case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; float deltaY = motionEvent.getRawY() - mDownY; if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) { mSwiping = true; mRefreshLayout.setEnabled(false); mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop); mRecyclerView.requestDisallowInterceptTouchEvent(true); // CancelLogin ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mRecyclerView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } if (mSwiping) { mDownView.setTranslationX(deltaX - mSwipingSlop); mDownView.setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; // setTranslationX(mDownView, deltaX); // setAlpha(mDownView, Math.max(0f, Math.min(1f, // 1f - 2f * Math.abs(deltaX) / mViewWidth))); // return true; } break; } } return false; }
From source file:net.osmand.plus.views.controls.SwipeDismissListViewTouchListener.java
@Override public boolean onTouch(View view, MotionEvent ev) { if (mViewWidth < 2) { mViewWidth = mListView.getWidth(); }/*from w w w.ja v a2s .c o m*/ switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mSwipePaused) { return false; } // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mListView.getChildCount(); int[] listViewCoords = new int[2]; mListView.getLocationOnScreen(listViewCoords); int x = (int) ev.getRawX() - listViewCoords[0]; int y = (int) ev.getRawY() - listViewCoords[1]; View child; for (int i = mListView.getHeaderViewsCount(); i < childCount; i++) { child = mListView.getChildAt(i); if (child != null) { child.getHitRect(rect); if (rect.contains(x, y)) { // if a specific swiping layout has been giving, use this to swipe. if (mSwipingLayout > 0) { View swipingView = child.findViewById(mSwipingLayout); if (swipingView != null) { mSwipeDownView = swipingView; mSwipeDownChild = child; break; } } // If no swiping layout has been found, swipe the whole child mSwipeDownView = mSwipeDownChild = child; break; } } } if (mSwipeDownView != null) { // test if the item should be swiped int position = mListView.getPositionForView(mSwipeDownView) - mListView.getHeaderViewsCount(); if (mCallbacks == null || mCallbacks.canDismiss(position)) { mDownX = ev.getRawX(); mDownY = ev.getRawY(); mDownPosition = position; mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(ev); } else { // set back to null to revert swiping mSwipeDownView = mSwipeDownChild = null; } } return false; } case MotionEvent.ACTION_CANCEL: { if (mVelocityTracker == null) { break; } if (mSwipeDownView != null && mSwiping) { // cancel ViewCompat.animate(mSwipeDownView).translationX(0).alpha(1).setDuration(mAnimationTime) .setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mSwipeDownView = mSwipeDownChild = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_UP: { if (mVelocityTracker == null) { break; } float deltaX = ev.getRawX() - mDownX; mVelocityTracker.addMovement(ev); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = Math.abs(mVelocityTracker.getXVelocity()); float velocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityY < velocityX && mSwiping && isSwipeDirectionValid(mVelocityTracker.getXVelocity()) && deltaX >= mViewWidth * 0.2f) { dismiss = true; dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss) { // dismiss slideOutView(mSwipeDownView, mSwipeDownChild, mDownPosition, dismissRight); } else if (mSwiping) { // Swipe back to regular position ViewCompat.animate(mSwipeDownView).translationX(0).alpha(1).setDuration(mAnimationTime) .setListener(null); } mVelocityTracker = null; mDownX = 0; mDownY = 0; mSwipeDownView = null; mSwipeDownChild = null; mDownPosition = AbsListView.INVALID_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mSwipePaused) { break; } mVelocityTracker.addMovement(ev); float deltaX = ev.getRawX() - mDownX; float deltaY = ev.getRawY() - mDownY; // Only start swipe in correct direction if (isSwipeDirectionValid(deltaX)) { ViewParent parent = mListView.getParent(); if (parent != null) { // If we swipe don't allow parent to intercept touch (e.g. like NavigationDrawer does) // otherwise swipe would not be working. parent.requestDisallowInterceptTouchEvent(true); } if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) { mSwiping = true; mListView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(ev); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (ev.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mListView.onTouchEvent(cancelEvent); } } else { // If we swiped into wrong direction, act like this was the new // touch down point mDownX = ev.getRawX(); deltaX = 0; } if (mSwiping) { ViewCompat.setTranslationX(mSwipeDownView, deltaX); ViewCompat.setAlpha(mSwipeDownView, Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } break; } } return false; }
From source file:com.me.harris.androidanimations._06_touch.swipelistview.SwipeListViewTouchListener.java
/** * @see View.OnTouchListener#onTouch(View, MotionEvent) *//*from w w w.j a v a 2 s. c o m*/ @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (viewWidth < 2) { viewWidth = swipeListView.getWidth(); } switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (paused) { return false; } swipeCurrentAction = SwipeListView.SWIPE_ACTION_NONE; int childCount = swipeListView.getChildCount(); int[] listViewCoords = new int[2]; swipeListView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; for (int i = 0; i < childCount; i++) { child = swipeListView.getChildAt(i); child.getHitRect(rect); if (rect.contains(x, y)) { setParentView(child); setFrontView(child.findViewById(swipeFrontView)); downX = motionEvent.getRawX(); downPosition = swipeListView.getPositionForView(child); frontView.setClickable(!opened.get(downPosition)); frontView.setLongClickable(!opened.get(downPosition)); velocityTracker = VelocityTracker.obtain(); velocityTracker.addMovement(motionEvent); if (swipeBackView > 0) { setBackView(child.findViewById(swipeBackView)); } break; } } view.onTouchEvent(motionEvent); return true; } case MotionEvent.ACTION_UP: { if (velocityTracker == null || !swiping) { break; } float deltaX = motionEvent.getRawX() - downX; velocityTracker.addMovement(motionEvent); velocityTracker.computeCurrentVelocity(1000); float velocityX = Math.abs(velocityTracker.getXVelocity()); if (!opened.get(downPosition)) { if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && velocityTracker.getXVelocity() > 0) { velocityX = 0; } if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && velocityTracker.getXVelocity() < 0) { velocityX = 0; } } float velocityY = Math.abs(velocityTracker.getYVelocity()); boolean swap = false; boolean swapRight = false; if (minFlingVelocity <= velocityX && velocityX <= maxFlingVelocity && velocityY < velocityX) { swapRight = velocityTracker.getXVelocity() > 0; if (opened.get(downPosition) && openedRight.get(downPosition) && swapRight) { swap = false; } else if (opened.get(downPosition) && !openedRight.get(downPosition) && !swapRight) { swap = false; } else { swap = true; } } else if (Math.abs(deltaX) > viewWidth / 2) { swap = true; swapRight = deltaX > 0; } generateAnimate(frontView, swap, swapRight, downPosition); velocityTracker.recycle(); velocityTracker = null; downX = 0; // change clickable front view if (swap) { frontView.setClickable(opened.get(downPosition)); frontView.setLongClickable(opened.get(downPosition)); } frontView = null; backView = null; this.downPosition = ListView.INVALID_POSITION; swiping = false; break; } case MotionEvent.ACTION_MOVE: { if (velocityTracker == null || paused) { break; } velocityTracker.addMovement(motionEvent); velocityTracker.computeCurrentVelocity(1000); float velocityX = Math.abs(velocityTracker.getXVelocity()); float velocityY = Math.abs(velocityTracker.getYVelocity()); float deltaX = motionEvent.getRawX() - downX; float deltaMode = Math.abs(deltaX); if (swipeMode == SwipeListView.SWIPE_MODE_NONE) { deltaMode = 0; } else if (swipeMode != SwipeListView.SWIPE_MODE_BOTH) { if (opened.get(downPosition)) { if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX < 0) { deltaMode = 0; } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX > 0) { deltaMode = 0; } } else { if (swipeMode == SwipeListView.SWIPE_MODE_LEFT && deltaX > 0) { deltaMode = 0; } else if (swipeMode == SwipeListView.SWIPE_MODE_RIGHT && deltaX < 0) { deltaMode = 0; } } } if (deltaMode > slop && swipeCurrentAction == SwipeListView.SWIPE_ACTION_NONE && velocityY < velocityX) { swiping = true; boolean swipingRight = (deltaX > 0); if (opened.get(downPosition)) { swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL; } else { if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_DISMISS) { swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS; } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_DISMISS) { swipeCurrentAction = SwipeListView.SWIPE_ACTION_DISMISS; } else if (swipingRight && swipeActionRight == SwipeListView.SWIPE_ACTION_CHECK) { swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHECK; } else if (!swipingRight && swipeActionLeft == SwipeListView.SWIPE_ACTION_CHECK) { swipeCurrentAction = SwipeListView.SWIPE_ACTION_CHECK; } else { swipeCurrentAction = SwipeListView.SWIPE_ACTION_REVEAL; } } swipeListView.requestDisallowInterceptTouchEvent(true); MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); swipeListView.onTouchEvent(cancelEvent); } if (swiping) { if (opened.get(downPosition)) { deltaX += openedRight.get(downPosition) ? viewWidth - rightOffset : -viewWidth + leftOffset; } move(deltaX); return true; } break; } } return false; }
From source file:com.android.internal.widget.ViewPager.java
@Override public boolean onTouchEvent(MotionEvent ev) { 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; }/* ww w . j ava 2 s . co m*/ 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 & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { mScroller.abortAnimation(); mPopulatePending = false; populate(); // Remember where the motion event started mLastMotionX = mInitialMotionX = ev.getX(); mLastMotionY = mInitialMotionY = ev.getY(); mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { final int pointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float y = ev.getY(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; requestParentDisallowInterceptTouchEvent(true); mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop : mInitialMotionX - mTouchSlop; mLastMotionY = y; setScrollState(SCROLL_STATE_DRAGGING); setScrollingCacheEnabled(true); // Disallow Parent Intercept, just in case ViewParent parent = getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } } // Not else! Note that mIsBeingDragged can be set above. if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(activePointerIndex); needsInvalidate |= performDrag(x); } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); final int initialVelocity = (int) velocityTracker.getXVelocity(mActivePointerId); mPopulatePending = true; final float scrollStart = getScrollStart(); final float scrolledPages = scrollStart / getPaddedWidth(); final ItemInfo ii = infoForFirstVisiblePage(); final int currentPage = ii.position; final float nextPageOffset; if (isLayoutRtl()) { nextPageOffset = (ii.offset - scrolledPages) / ii.widthFactor; } else { nextPageOffset = (scrolledPages - ii.offset) / ii.widthFactor; } final int activePointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(activePointerIndex); final int totalDelta = (int) (x - mInitialMotionX); final int nextPage = determineTargetPage(currentPage, nextPageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); mActivePointerId = INVALID_POINTER; endDrag(); mLeftEdge.onRelease(); mRightEdge.onRelease(); needsInvalidate = true; } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { scrollToItem(mCurItem, true, 0, false); mActivePointerId = INVALID_POINTER; endDrag(); mLeftEdge.onRelease(); mRightEdge.onRelease(); needsInvalidate = true; } break; case MotionEvent.ACTION_POINTER_DOWN: { final int index = ev.getActionIndex(); final float x = ev.getX(index); mLastMotionX = x; mActivePointerId = ev.getPointerId(index); break; } case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId)); break; } if (needsInvalidate) { postInvalidateOnAnimation(); } return true; }
From source file:com.glview.widget.AbsListView.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(); }/*from www. j a va2 s.c om*/ if (mPositionScroller != null) { mPositionScroller.stop(); } if (mIsDetaching || !isAttachedToWindow()) { // 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; } startNestedScroll(SCROLL_AXIS_VERTICAL); if (mFastScroll != null) { boolean intercepted = mFastScroll.onTouchEvent(ev); if (intercepted) { return true; } } initVelocityTrackerIfNotExists(); final MotionEvent vtev = MotionEvent.obtain(ev); final int actionMasked = ev.getActionMasked(); if (actionMasked == MotionEvent.ACTION_DOWN) { mNestedYOffset = 0; } vtev.offsetLocation(0, mNestedYOffset); switch (actionMasked) { case MotionEvent.ACTION_DOWN: { onTouchDown(ev); break; } case MotionEvent.ACTION_MOVE: { onTouchMove(ev, vtev); break; } case MotionEvent.ACTION_UP: { onTouchUp(ev); break; } case MotionEvent.ACTION_CANCEL: { onTouchCancel(); break; } case MotionEvent.ACTION_POINTER_UP: { onSecondaryPointerUp(ev); final int x = mMotionX; final int y = mMotionY; final int motionPosition = pointToPosition(x, y); if (motionPosition >= 0) { // Remember where the motion event started final View child = getChildAt(motionPosition - mFirstPosition); mMotionViewOriginalTop = child.getTop(); mMotionPosition = motionPosition; } mLastY = y; break; } case MotionEvent.ACTION_POINTER_DOWN: { // New pointers take over dragging duties final int index = ev.getActionIndex(); final int id = ev.getPointerId(index); final int x = (int) ev.getX(index); final int y = (int) ev.getY(index); mMotionCorrection = 0; mActivePointerId = id; mMotionX = x; mMotionY = y; final int motionPosition = pointToPosition(x, y); if (motionPosition >= 0) { // Remember where the motion event started final View child = getChildAt(motionPosition - mFirstPosition); mMotionViewOriginalTop = child.getTop(); mMotionPosition = motionPosition; } mLastY = y; break; } } if (mVelocityTracker != null) { mVelocityTracker.addMovement(vtev); } vtev.recycle(); return true; }
From source file:com.mylikes.likes.etchasketch.Slate.java
@SuppressLint("NewApi") @Override/*w w w .j a v a 2s . 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:com.antew.redditinpictures.library.widget.SwipeListView.java
@Override public boolean onTouchEvent(MotionEvent event) { // Store width of this list for usage of swipe distance detection if (mViewWidth < 2) { mViewWidth = getWidth();//from w ww . j ava 2s . c o m } switch (MotionEventCompat.getActionMasked(event)) { case MotionEvent.ACTION_DOWN: int[] viewCoords = new int[2]; // Figure out where the touch occurred. getLocationOnScreen(viewCoords); int touchX = (int) event.getRawX() - viewCoords[0]; int touchY = (int) event.getRawY() - viewCoords[1]; Rect rect = new Rect(); View child; int childCount = getChildCount(); for (int i = getHeaderViewsCount(); i <= childCount; i++) { // Go through each child view (excluding headers) and see if our touch pressed it. child = getChildAt(i); if (child != null) { //Get the child hit rectangle. child.getHitRect(rect); //If the child would be hit by this press. if (rect.contains(touchX, touchY)) { // DIRECT HIT! You sunk my battleship. Now that we know which view was touched, store it off for use if a move occurs. View frontView = child.findViewById(mFrontViewId); View backView = child.findViewById(mBackViewId); // Create our view pair. mViewPair = new SwipeableViewPair(frontView, backView); break; } } } if (mViewPair != null) { // If we have a view pair, record details about the inital touch for use later. mDownX = event.getRawX(); mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(event); } break; case MotionEvent.ACTION_UP: if (mVelocityTracker != null) { // Add the movement so we can calculate velocity. mVelocityTracker.addMovement(event); mVelocityTracker.computeCurrentVelocity(1000); float deltaX = event.getRawX() - mDownX; float velocityX = Math.abs(mVelocityTracker.getXVelocity()); float velocityY = Math.abs(mVelocityTracker.getYVelocity()); if (mViewPair != null) { boolean shouldSwipe = false; // If the view has been moved a significant enough distance or if the view was flung, check to see if we should swipe it. if ((Math.abs(deltaX) > mViewWidth / 2 && mState == State.SWIPING) || (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityX > velocityY)) { if (mSwipeDirection == SWIPE_DIRECTION_BOTH) { // If the list is setup to swipe in either direction, just let it go. shouldSwipe = true; } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) { // If the list is only setup to swipe left, then only allow swiping to the left. shouldSwipe = true; } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) { // If the list is only setup to swipe right, then only allow swiping to the right. shouldSwipe = true; } } if (shouldSwipe) { // If a swipe should occur meaning someone has let go of a view they were moving and it was far/fast enough for us to consider it a swipe start the animations. mViewPair.mFrontView.animate().translationX(deltaX >= 0 ? mViewWidth : -mViewWidth).alpha(0) .setDuration(mAnimationTime); mViewPair.mBackView.animate().alpha(1).setDuration(mAnimationTime); // Now that the item is open, store it off so we can close it when we scroll if needed. mSwipedViews.put(mViewPair.hashCode(), mViewPair); // Clear out current variables as they are no longer needed and recycle the velocity tracker. resetState(); } else { // If the user let go of the view and we don't think the swipe was intended to occur (it was cancelled basically) reset the views. // Make sure the back disappears, since if it has buttons these can intercept touches from the front view. mViewPair.mBackView.setVisibility(View.GONE); mViewPair.mFrontView.animate().translationX(0).alpha(1).setDuration(mAnimationTime); // Clear out current variables as they are no longer needed and recycle the velocity tracker. resetState(); } } } break; case MotionEvent.ACTION_MOVE: if (mVelocityTracker != null && mState != State.SCROLLING) { // If this is an initial movement and we aren't already swiping. // Add the movement so we can calculate velocity. mVelocityTracker.addMovement(event); mVelocityTracker.computeCurrentVelocity(1000); float deltaX = event.getRawX() - mDownX; float velocityX = Math.abs(mVelocityTracker.getXVelocity()); float velocityY = Math.abs(mVelocityTracker.getYVelocity()); // If the movement has been more than what is considered slop, and they are clearing moving horizontal not vertical. if (Math.abs(deltaX) > mTouchSlop && velocityX > velocityY) { boolean initiateSwiping = false; if (mSwipeDirection == SWIPE_DIRECTION_BOTH) { // If the list is setup to swipe in either direction, just let it go. initiateSwiping = true; } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) { // If the list is only setup to swipe left, then only allow swiping to the left. initiateSwiping = true; } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) { // If the list is only setup to swipe right, then only allow swiping to the right. initiateSwiping = true; } if (initiateSwiping) { ViewParent parent = getParent(); if (parent != null) { // Don't allow parent to intercept touch (prevents NavigationDrawers from intercepting when near the bezel). parent.requestDisallowInterceptTouchEvent(true); } // Change our state to swiping to start tranforming the item. changeState(State.SWIPING); // Make sure that touches aren't intercepted. requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch to prevent it from being focused. MotionEvent cancelEvent = MotionEvent.obtain(event); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); super.onTouchEvent(cancelEvent); } else { // Otherwise we need to cancel the touch event to prevent accidentally selecting the item and also preventing the swipe in the wrong direction or an incomplete touch from moving the view. MotionEvent cancelEvent = MotionEvent.obtain(event); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); super.onTouchEvent(cancelEvent); } } if (mState == State.SWIPING && mViewPair != null) { // Make sure the back is visible. mViewPair.mBackView.setVisibility(View.VISIBLE); //Fade the back in and front out as they move. mViewPair.mBackView.setAlpha(Math.min(1f, 2f * Math.abs(deltaX) / mViewWidth)); mViewPair.mFrontView.setTranslationX(deltaX); mViewPair.mFrontView .setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } } break; } return super.onTouchEvent(event); }
From source file:com.itude.mobile.mobbl.blueprint.app.view.listeners.SwipeDismissRecyclerViewTouchListener.java
@Override public boolean onTouch(View view, MotionEvent motionEvent) { if (mViewWidth < 2) { mViewWidth = mIsVertical ? mRecyclerView.getHeight() : mRecyclerView.getWidth(); }//from w w w . jav a 2s . c o m switch (motionEvent.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mPaused) { return false; } // TODO: ensure this is a finger, and set a flag // Find the child view that was touched (perform a hit test) Rect rect = new Rect(); int childCount = mRecyclerView.getChildCount(); int[] listViewCoords = new int[2]; mRecyclerView.getLocationOnScreen(listViewCoords); int x = (int) motionEvent.getRawX() - listViewCoords[0]; int y = (int) motionEvent.getRawY() - listViewCoords[1]; View child; mDownView = mRecyclerView.findChildViewUnder(x, y); if (mDownView != null) { mDownX = motionEvent.getRawX(); mDownY = motionEvent.getRawY(); mDownPosition = mRecyclerView.getChildPosition(mDownView); if (mCallbacks.canDismiss(mDownPosition)) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(motionEvent); } else { mDownView = null; } } return false; } case MotionEvent.ACTION_CANCEL: { if (mVelocityTracker == null) { break; } if (mDownView != null && mSwiping) { // cancel if (mIsVertical) { mDownView.animate().translationY(0).alpha(1).setDuration(mAnimationTime).setListener(null); } else { mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); } } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = RecyclerView.NO_POSITION; mSwiping = false; break; } case MotionEvent.ACTION_UP: { if (!mSwiping && mDownView != null && mItemTouchCallback != null) { mItemTouchCallback.onTouch(mRecyclerView.getChildPosition(mDownView)); mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; return true; } if (mVelocityTracker == null) { break; } float deltaX = motionEvent.getRawX() - mDownX; float deltaY = motionEvent.getRawY() - mDownY; mVelocityTracker.addMovement(motionEvent); mVelocityTracker.computeCurrentVelocity(1000); float velocityX = mVelocityTracker.getXVelocity(); float velocityY = mVelocityTracker.getYVelocity(); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(mVelocityTracker.getYVelocity()); boolean dismiss = false; boolean dismissRight = false; if (mIsVertical) { if (Math.abs(deltaY) > mViewWidth / 2 && mSwiping) { dismiss = true; dismissRight = deltaY > 0; } else if (mMinFlingVelocity <= absVelocityY && absVelocityY <= mMaxFlingVelocity && absVelocityX < absVelocityY && mSwiping) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityY < 0) == (deltaY < 0); dismissRight = mVelocityTracker.getYVelocity() > 0; } if (dismiss && mDownPosition != ListView.INVALID_POSITION) { // dismiss final View downView = mDownView; // mDownView gets null'd before animation ends final int downPosition = mDownPosition; ++mDismissAnimationRefCount; mDownView.animate().translationY(dismissRight ? mViewWidth : -mViewWidth).alpha(0) .setDuration(mAnimationTime).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); } else { // cancel mDownView.animate().translationY(0).alpha(1).setDuration(mAnimationTime).setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; } else { if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) { dismiss = true; dismissRight = deltaX > 0; } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity && absVelocityY < absVelocityX && mSwiping) { // dismiss only if flinging in the same direction as dragging dismiss = (velocityX < 0) == (deltaX < 0); dismissRight = mVelocityTracker.getXVelocity() > 0; } if (dismiss && mDownPosition != ListView.INVALID_POSITION) { // dismiss final View downView = mDownView; // mDownView gets null'd before animation ends final int downPosition = mDownPosition; ++mDismissAnimationRefCount; mDownView.animate().translationX(dismissRight ? mViewWidth : -mViewWidth).alpha(0) .setDuration(mAnimationTime).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { performDismiss(downView, downPosition); } }); } else { // cancel mDownView.animate().translationX(0).alpha(1).setDuration(mAnimationTime).setListener(null); } mVelocityTracker.recycle(); mVelocityTracker = null; mDownX = 0; mDownY = 0; mDownView = null; mDownPosition = ListView.INVALID_POSITION; mSwiping = false; } break; } case MotionEvent.ACTION_MOVE: { if (mVelocityTracker == null || mPaused) { break; } mVelocityTracker.addMovement(motionEvent); float deltaX = motionEvent.getRawX() - mDownX; float deltaY = motionEvent.getRawY() - mDownY; if (mIsVertical) { if (Math.abs(deltaY) > mSlop && Math.abs(deltaX) < Math.abs(deltaY) / 2) { mSwiping = true; mSwipingSlop = (deltaY > 0 ? mSlop : -mSlop); mRecyclerView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mRecyclerView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } if (mSwiping) { mDownView.setTranslationY(deltaY - mSwipingSlop); mDownView.setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaY) / mViewWidth))); return true; } } else { if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) { mSwiping = true; mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop); mRecyclerView.requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch (un-highlighting the item) MotionEvent cancelEvent = MotionEvent.obtain(motionEvent); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); mRecyclerView.onTouchEvent(cancelEvent); cancelEvent.recycle(); } if (mSwiping) { mDownView.setTranslationX(deltaX - mSwipingSlop); mDownView.setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } } break; } } return false; }
From source file:com.davidtpate.swipelistview.SwipeListView.java
@Override public boolean onTouchEvent(MotionEvent event) { // Store width of this list for usage of swipe distance detection if (mViewWidth < 2) { mViewWidth = getWidth();/*w w w . ja v a 2 s . c o m*/ } switch (MotionEventCompat.getActionMasked(event)) { case MotionEvent.ACTION_DOWN: int[] viewCoords = new int[2]; // Figure out where the touch occurred. getLocationOnScreen(viewCoords); int touchX = (int) event.getRawX() - viewCoords[0]; int touchY = (int) event.getRawY() - viewCoords[1]; Rect rect = new Rect(); View child; int childCount = getChildCount(); for (int i = getHeaderViewsCount(); i <= childCount; i++) { // Go through each child view (excluding headers) and see if our touch pressed it. child = getChildAt(i); if (child != null) { //Get the child hit rectangle. child.getHitRect(rect); //If the child would be hit by this press. if (rect.contains(touchX, touchY)) { // DIRECT HIT! You sunk my battleship. Now that we know which view was touched, store it off for use if a move occurs. View frontView = child.findViewById(mFrontViewId); View backView = child.findViewById(mBackViewId); // Create our view pair. mViewPair = new SwipeableViewPair(frontView, backView); break; } } } if (mViewPair != null) { // If we have a view pair, record details about the inital touch for use later. mDownX = event.getRawX(); mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.addMovement(event); } break; case MotionEvent.ACTION_UP: if (mVelocityTracker != null) { // Add the movement so we can calculate velocity. mVelocityTracker.addMovement(event); mVelocityTracker.computeCurrentVelocity(1000); float deltaX = event.getRawX() - mDownX; float velocityX = Math.abs(mVelocityTracker.getXVelocity()); float velocityY = Math.abs(mVelocityTracker.getYVelocity()); if (mViewPair != null) { boolean shouldSwipe = false; // If the view has been moved a significant enough distance or if the view was flung, check to see if we should swipe it. if ((Math.abs(deltaX) > mViewWidth / 2 && mState == State.SWIPING) || (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityX > velocityY)) { if (mSwipeDirection == SWIPE_DIRECTION_BOTH) { // If the list is setup to swipe in either direction, just let it go. shouldSwipe = true; } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) { // If the list is only setup to swipe left, then only allow swiping to the left. shouldSwipe = true; } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) { // If the list is only setup to swipe right, then only allow swiping to the right. shouldSwipe = true; } } if (shouldSwipe) { // If a swipe should occur meaning someone has let go of a view they were moving and it was far/fast enough for us to consider it a swipe start the animations. ViewPropertyAnimator.animate(mViewPair.mFrontView) .translationX(deltaX >= 0 ? mViewWidth : -mViewWidth).alpha(0) .setDuration(mAnimationTime); ViewPropertyAnimator.animate(mViewPair.mBackView).alpha(1).setDuration(mAnimationTime); // Now that the item is open, store it off so we can close it when we scroll if needed. mSwipedViews.put(mViewPair.hashCode(), mViewPair); // Clear out current variables as they are no longer needed and recycle the velocity tracker. resetState(); } else { // If the user let go of the view and we don't think the swipe was intended to occur (it was cancelled basically) reset the views. // Make sure the back disappears, since if it has buttons these can intercept touches from the front view. mViewPair.mBackView.setVisibility(View.GONE); ViewPropertyAnimator.animate(mViewPair.mFrontView).translationX(0).alpha(1) .setDuration(mAnimationTime); // Clear out current variables as they are no longer needed and recycle the velocity tracker. resetState(); } } } break; case MotionEvent.ACTION_MOVE: if (mVelocityTracker != null && mState != State.SCROLLING) { // If this is an initial movement and we aren't already swiping. // Add the movement so we can calculate velocity. mVelocityTracker.addMovement(event); mVelocityTracker.computeCurrentVelocity(1000); float deltaX = event.getRawX() - mDownX; float velocityX = Math.abs(mVelocityTracker.getXVelocity()); float velocityY = Math.abs(mVelocityTracker.getYVelocity()); // If the movement has been more than what is considered slop, and they are clearing moving horizontal not vertical. if (Math.abs(deltaX) > mTouchSlop && velocityX > velocityY) { boolean initiateSwiping = false; if (mSwipeDirection == SWIPE_DIRECTION_BOTH) { // If the list is setup to swipe in either direction, just let it go. initiateSwiping = true; } else if (mSwipeDirection == SWIPE_DIRECTION_LEFT && deltaX < 0) { // If the list is only setup to swipe left, then only allow swiping to the left. initiateSwiping = true; } else if (mSwipeDirection == SWIPE_DIRECTION_RIGHT && deltaX > 0) { // If the list is only setup to swipe right, then only allow swiping to the right. initiateSwiping = true; } if (initiateSwiping) { ViewParent parent = getParent(); if (parent != null) { // Don't allow parent to intercept touch (prevents NavigationDrawers from intercepting when near the bezel). parent.requestDisallowInterceptTouchEvent(true); } // Change our state to swiping to start tranforming the item. changeState(State.SWIPING); // Make sure that touches aren't intercepted. requestDisallowInterceptTouchEvent(true); // Cancel ListView's touch to prevent it from being focused. MotionEvent cancelEvent = MotionEvent.obtain(event); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); super.onTouchEvent(cancelEvent); } else { // Otherwise we need to cancel the touch event to prevent accidentally selecting the item and also preventing the swipe in the wrong direction or an incomplete touch from moving the view. MotionEvent cancelEvent = MotionEvent.obtain(event); cancelEvent.setAction(MotionEvent.ACTION_CANCEL | (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT)); super.onTouchEvent(cancelEvent); } } if (mState == State.SWIPING && mViewPair != null) { // Make sure the back is visible. mViewPair.mBackView.setVisibility(View.VISIBLE); //Fade the back in and front out as they move. ViewHelper.setAlpha(mViewPair.mBackView, Math.min(1f, 2f * Math.abs(deltaX) / mViewWidth)); ViewHelper.setTranslationX(mViewPair.mFrontView, deltaX); ViewHelper.setAlpha(mViewPair.mFrontView, Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth))); return true; } } break; } return super.onTouchEvent(event); }