Created
August 17, 2020 02:35
-
-
Save yuriyskulskiy/74a49c87c64d8418eb122d02cb1dd57d to your computer and use it in GitHub Desktop.
AnimatedLayout part 3: update onTouch() method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
public boolean onTouchEvent(MotionEvent event) { | |
isTouching = true; | |
mFling.cancel(); | |
switch (event.getActionMasked()) { | |
case MotionEvent.ACTION_DOWN: | |
mPreviousTouchX = event.getX(); | |
if (mVelocityTracker == null) { | |
// Retrieve a new VelocityTracker object to watch the velocity | |
// of a motion. | |
mVelocityTracker = VelocityTracker.obtain(); | |
} else { | |
// Reset the velocity tracker back to its initial state. | |
mVelocityTracker.clear(); | |
} | |
mVelocityTracker.addMovement(event); | |
return true; | |
case MotionEvent.ACTION_MOVE: | |
mVelocityTracker.addMovement(event); | |
... | |
return true; | |
case MotionEvent.ACTION_CANCEL: | |
case MotionEvent.ACTION_UP: | |
if (needToFling()) { | |
mVelocityTracker.addMovement(event); | |
mVelocityTracker.computeCurrentVelocity(1000); | |
float velocityX = mVelocityTracker.getXVelocity(); | |
if (Math.abs(velocityX) < mCurrentMinFlingVelocityPx) { | |
if (mOffsetValue < getWidth() / 2f) { | |
velocityX = -mCurrentMinFlingVelocityPx; | |
} else { | |
velocityX = +mCurrentMinFlingVelocityPx; | |
} | |
} | |
mFling.setStartVelocity(velocityX) | |
.setMinValue(0) | |
.setMaxValue(getWidth()) | |
.setFriction(0.1f) | |
.start(); | |
mPreviousTouchX = -1; | |
} else { | |
applyIdleState(); | |
invalidate(); | |
} | |
if (mVelocityTracker != null) { | |
mVelocityTracker.recycle(); | |
mVelocityTracker = null; | |
} | |
isTouching = false; | |
return true; | |
default: | |
return false; | |
} | |
} | |
private boolean needToFling() { | |
return 0 < mOffsetValue && mOffsetValue < getWidth(); | |
} | |
private void applyIdleState() { | |
mCurrentAnimation = IDLE_ANIMATION_STATE; | |
mPreviousTouchX = -1; | |
if (mOffsetValue < getWidth() / 2f) { | |
mIdleState = WINTER_STATE; | |
updateOffset(0); | |
applyWinter(); | |
} else { | |
mIdleState = SUMMER_STATE; | |
updateOffset(getWidth()); | |
applySummer(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment