OverScroller.java revision 637d337b58d8eec6de19230a5dd5ca5581c0478d
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.widget; 18 19import android.content.Context; 20import android.graphics.Interpolator; 21import android.view.ViewConfiguration; 22import android.view.animation.AnimationUtils; 23 24/** 25 * This class encapsulates scrolling with the ability to overshoot the bounds 26 * of a scrolling operation. This class is a drop-in replacement for 27 * {@link android.widget.Scroller} in most cases. 28 */ 29public class OverScroller { 30 int mMode; 31 32 private final MagneticOverScroller mScrollerX; 33 private final MagneticOverScroller mScrollerY; 34 35 private float mDeceleration; 36 private final float mPpi; 37 private final boolean mFlywheel; 38 39 private static float DECELERATION_RATE = (float) (Math.log(0.75) / Math.log(0.9)); 40 private static float ALPHA = 800; // pixels / seconds 41 private static float START_TENSION = 0.4f; // Tension at start: (0.4 * total T, 1.0 * Distance) 42 private static float END_TENSION = 1.0f - START_TENSION; 43 private static final int NB_SAMPLES = 100; 44 private static final float[] SPLINE_POSITION = new float[NB_SAMPLES + 1]; 45 private static final float[] SPLINE_TIME = new float[NB_SAMPLES + 1]; 46 47 private static final int DEFAULT_DURATION = 250; 48 private static final int SCROLL_MODE = 0; 49 private static final int FLING_MODE = 1; 50 51 static { 52 float x_min = 0.0f; 53 float y_min = 0.0f; 54 for (int i = 0; i < NB_SAMPLES; i++) { 55 final float alpha = (float) i / NB_SAMPLES; 56 { 57 float x_max = 1.0f; 58 float x, tx, coef; 59 while (true) { 60 x = x_min + (x_max - x_min) / 2.0f; 61 coef = 3.0f * x * (1.0f - x); 62 tx = coef * ((1.0f - x) * START_TENSION + x * END_TENSION) + x * x * x; 63 if (Math.abs(tx - alpha) < 1E-5) break; 64 if (tx > alpha) x_max = x; 65 else x_min = x; 66 } 67 SPLINE_POSITION[i] = coef + x * x * x; 68 } 69 70 { 71 float y_max = 1.0f; 72 float y, dy, coef; 73 while (true) { 74 y = y_min + (y_max - y_min) / 2.0f; 75 coef = 3.0f * y * (1.0f - y); 76 dy = coef + y * y * y; 77 if (Math.abs(dy - alpha) < 1E-5) break; 78 if (dy > alpha) y_max = y; 79 else y_min = y; 80 } 81 SPLINE_TIME[i] = coef * ((1.0f - y) * START_TENSION + y * END_TENSION) + y * y * y; 82 } 83 } 84 SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] = 1.0f; 85 } 86 87 public OverScroller(Context context) { 88 this(context, null, 0.f, 0.f, true); 89 } 90 91 /** 92 * Creates an OverScroller. 93 * @param context The context of this application. 94 * @param interpolator The scroll interpolator. If null, a default (viscous) interpolator will 95 * be used. 96 * @param bounceCoefficientX A value between 0 and 1 that will determine the proportion of the 97 * velocity which is preserved in the bounce when the horizontal edge is reached. A null value 98 * means no bounce. 99 * @param bounceCoefficientY Same as bounceCoefficientX but for the vertical direction. 100 */ 101 public OverScroller(Context context, Interpolator interpolator, 102 float bounceCoefficientX, float bounceCoefficientY, boolean flywheel) { 103 mFlywheel = flywheel; 104 mPpi = context.getResources().getDisplayMetrics().density * 160.0f; 105 mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction()); 106 mScrollerX = new MagneticOverScroller(); 107 mScrollerY = new MagneticOverScroller(); 108 109 mScrollerX.setBounceCoefficient(bounceCoefficientX); 110 mScrollerY.setBounceCoefficient(bounceCoefficientY); 111 } 112 113 114 /** 115 * The amount of friction applied to flings. The default value 116 * is {@link ViewConfiguration#getScrollFriction}. 117 * 118 * @param friction A scalar dimension-less value representing the coefficient of 119 * friction. 120 */ 121 public final void setFriction(float friction) { 122 mDeceleration = computeDeceleration(friction); 123 } 124 125 private float computeDeceleration(float friction) { 126 return 9.81f // g (m/s^2) 127 * 39.37f // inch/meter 128 * mPpi // pixels per inch 129 * friction; 130 } 131 132 /** 133 * 134 * Returns whether the scroller has finished scrolling. 135 * 136 * @return True if the scroller has finished scrolling, false otherwise. 137 */ 138 public final boolean isFinished() { 139 return mScrollerX.mFinished && mScrollerY.mFinished; 140 } 141 142 /** 143 * Force the finished field to a particular value. Contrary to 144 * {@link #abortAnimation()}, forcing the animation to finished 145 * does NOT cause the scroller to move to the final x and y 146 * position. 147 * 148 * @param finished The new finished value. 149 */ 150 public final void forceFinished(boolean finished) { 151 mScrollerX.mFinished = mScrollerY.mFinished = finished; 152 } 153 154 /** 155 * Returns the current X offset in the scroll. 156 * 157 * @return The new X offset as an absolute distance from the origin. 158 */ 159 public final int getCurrX() { 160 return mScrollerX.mCurrentPosition; 161 } 162 163 /** 164 * Returns the current Y offset in the scroll. 165 * 166 * @return The new Y offset as an absolute distance from the origin. 167 */ 168 public final int getCurrY() { 169 return mScrollerY.mCurrentPosition; 170 } 171 172 /** 173 * @hide 174 * Returns the current velocity. 175 * 176 * @return The original velocity less the deceleration, norm of the X and Y velocity vector. 177 */ 178 public float getCurrVelocity() { 179 float squaredNorm = mScrollerX.mCurrVelocity * mScrollerX.mCurrVelocity; 180 squaredNorm += mScrollerY.mCurrVelocity * mScrollerY.mCurrVelocity; 181 return (float) Math.sqrt(squaredNorm); 182 } 183 184 /** 185 * Returns the start X offset in the scroll. 186 * 187 * @return The start X offset as an absolute distance from the origin. 188 */ 189 public final int getStartX() { 190 return mScrollerX.mStart; 191 } 192 193 /** 194 * Returns the start Y offset in the scroll. 195 * 196 * @return The start Y offset as an absolute distance from the origin. 197 */ 198 public final int getStartY() { 199 return mScrollerY.mStart; 200 } 201 202 /** 203 * Returns where the scroll will end. Valid only for "fling" scrolls. 204 * 205 * @return The final X offset as an absolute distance from the origin. 206 */ 207 public final int getFinalX() { 208 return mScrollerX.mFinal; 209 } 210 211 /** 212 * Returns where the scroll will end. Valid only for "fling" scrolls. 213 * 214 * @return The final Y offset as an absolute distance from the origin. 215 */ 216 public final int getFinalY() { 217 return mScrollerY.mFinal; 218 } 219 220 /** 221 * Returns how long the scroll event will take, in milliseconds. 222 * 223 * @return The duration of the scroll in milliseconds. 224 * 225 * @hide Pending removal once nothing depends on it 226 * @deprecated OverScrollers don't necessarily have a fixed duration. 227 * This function will lie to the best of its ability. 228 */ 229 @Deprecated 230 public final int getDuration() { 231 return Math.max(mScrollerX.mDuration, mScrollerY.mDuration); 232 } 233 234 /** 235 * Extend the scroll animation. This allows a running animation to scroll 236 * further and longer, when used with {@link #setFinalX(int)} or {@link #setFinalY(int)}. 237 * 238 * @param extend Additional time to scroll in milliseconds. 239 * @see #setFinalX(int) 240 * @see #setFinalY(int) 241 * 242 * @hide Pending removal once nothing depends on it 243 * @deprecated OverScrollers don't necessarily have a fixed duration. 244 * Instead of setting a new final position and extending 245 * the duration of an existing scroll, use startScroll 246 * to begin a new animation. 247 */ 248 @Deprecated 249 public void extendDuration(int extend) { 250 mScrollerX.extendDuration(extend); 251 mScrollerY.extendDuration(extend); 252 } 253 254 /** 255 * Sets the final position (X) for this scroller. 256 * 257 * @param newX The new X offset as an absolute distance from the origin. 258 * @see #extendDuration(int) 259 * @see #setFinalY(int) 260 * 261 * @hide Pending removal once nothing depends on it 262 * @deprecated OverScroller's final position may change during an animation. 263 * Instead of setting a new final position and extending 264 * the duration of an existing scroll, use startScroll 265 * to begin a new animation. 266 */ 267 @Deprecated 268 public void setFinalX(int newX) { 269 mScrollerX.setFinalPosition(newX); 270 } 271 272 /** 273 * Sets the final position (Y) for this scroller. 274 * 275 * @param newY The new Y offset as an absolute distance from the origin. 276 * @see #extendDuration(int) 277 * @see #setFinalX(int) 278 * 279 * @hide Pending removal once nothing depends on it 280 * @deprecated OverScroller's final position may change during an animation. 281 * Instead of setting a new final position and extending 282 * the duration of an existing scroll, use startScroll 283 * to begin a new animation. 284 */ 285 @Deprecated 286 public void setFinalY(int newY) { 287 mScrollerY.setFinalPosition(newY); 288 } 289 290 /** 291 * Call this when you want to know the new location. If it returns true, the 292 * animation is not yet finished. 293 */ 294 public boolean computeScrollOffset() { 295 if (isFinished()) { 296 return false; 297 } 298 299 switch (mMode) { 300 case SCROLL_MODE: 301 long time = AnimationUtils.currentAnimationTimeMillis(); 302 // Any scroller can be used for time, since they were started 303 // together in scroll mode. We use X here. 304 final long elapsedTime = time - mScrollerX.mStartTime; 305 306 final int duration = mScrollerX.mDuration; 307 if (elapsedTime < duration) { 308 float q = (float) (elapsedTime) / duration; 309 310 q = Scroller.viscousFluid(q); 311 312 mScrollerX.updateScroll(q); 313 mScrollerY.updateScroll(q); 314 } else { 315 abortAnimation(); 316 } 317 break; 318 319 case FLING_MODE: 320 if (!mScrollerX.mFinished) { 321 if (!mScrollerX.update()) { 322 if (!mScrollerX.continueWhenFinished()) { 323 mScrollerX.finish(); 324 } 325 } 326 } 327 328 if (!mScrollerY.mFinished) { 329 if (!mScrollerY.update()) { 330 if (!mScrollerY.continueWhenFinished()) { 331 mScrollerY.finish(); 332 } 333 } 334 } 335 336 break; 337 } 338 339 return true; 340 } 341 342 /** 343 * Start scrolling by providing a starting point and the distance to travel. 344 * The scroll will use the default value of 250 milliseconds for the 345 * duration. 346 * 347 * @param startX Starting horizontal scroll offset in pixels. Positive 348 * numbers will scroll the content to the left. 349 * @param startY Starting vertical scroll offset in pixels. Positive numbers 350 * will scroll the content up. 351 * @param dx Horizontal distance to travel. Positive numbers will scroll the 352 * content to the left. 353 * @param dy Vertical distance to travel. Positive numbers will scroll the 354 * content up. 355 */ 356 public void startScroll(int startX, int startY, int dx, int dy) { 357 startScroll(startX, startY, dx, dy, DEFAULT_DURATION); 358 } 359 360 /** 361 * Start scrolling by providing a starting point and the distance to travel. 362 * 363 * @param startX Starting horizontal scroll offset in pixels. Positive 364 * numbers will scroll the content to the left. 365 * @param startY Starting vertical scroll offset in pixels. Positive numbers 366 * will scroll the content up. 367 * @param dx Horizontal distance to travel. Positive numbers will scroll the 368 * content to the left. 369 * @param dy Vertical distance to travel. Positive numbers will scroll the 370 * content up. 371 * @param duration Duration of the scroll in milliseconds. 372 */ 373 public void startScroll(int startX, int startY, int dx, int dy, int duration) { 374 mMode = SCROLL_MODE; 375 mScrollerX.startScroll(startX, dx, duration); 376 mScrollerY.startScroll(startY, dy, duration); 377 } 378 379 /** 380 * Call this when you want to 'spring back' into a valid coordinate range. 381 * 382 * @param startX Starting X coordinate 383 * @param startY Starting Y coordinate 384 * @param minX Minimum valid X value 385 * @param maxX Maximum valid X value 386 * @param minY Minimum valid Y value 387 * @param maxY Minimum valid Y value 388 * @return true if a springback was initiated, false if startX and startY were 389 * already within the valid range. 390 */ 391 public boolean springBack(int startX, int startY, int minX, int maxX, int minY, int maxY) { 392 mMode = FLING_MODE; 393 394 // Make sure both methods are called. 395 final boolean spingbackX = mScrollerX.springback(startX, minX, maxX); 396 final boolean spingbackY = mScrollerY.springback(startY, minY, maxY); 397 return spingbackX || spingbackY; 398 } 399 400 public void fling(int startX, int startY, int velocityX, int velocityY, 401 int minX, int maxX, int minY, int maxY) { 402 fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, 0, 0); 403 } 404 405 /** 406 * Start scrolling based on a fling gesture. The distance traveled will 407 * depend on the initial velocity of the fling. 408 * 409 * @param startX Starting point of the scroll (X) 410 * @param startY Starting point of the scroll (Y) 411 * @param velocityX Initial velocity of the fling (X) measured in pixels per 412 * second. 413 * @param velocityY Initial velocity of the fling (Y) measured in pixels per 414 * second 415 * @param minX Minimum X value. The scroller will not scroll past this point 416 * unless overX > 0. If overfling is allowed, it will use minX as 417 * a springback boundary. 418 * @param maxX Maximum X value. The scroller will not scroll past this point 419 * unless overX > 0. If overfling is allowed, it will use maxX as 420 * a springback boundary. 421 * @param minY Minimum Y value. The scroller will not scroll past this point 422 * unless overY > 0. If overfling is allowed, it will use minY as 423 * a springback boundary. 424 * @param maxY Maximum Y value. The scroller will not scroll past this point 425 * unless overY > 0. If overfling is allowed, it will use maxY as 426 * a springback boundary. 427 * @param overX Overfling range. If > 0, horizontal overfling in either 428 * direction will be possible. 429 * @param overY Overfling range. If > 0, vertical overfling in either 430 * direction will be possible. 431 */ 432 public void fling(int startX, int startY, int velocityX, int velocityY, 433 int minX, int maxX, int minY, int maxY, int overX, int overY) { 434 // Continue a scroll or fling in progress 435 if (mFlywheel && !isFinished()) { 436 float oldVelocityX = mScrollerX.mCurrVelocity; 437 float oldVelocityY = mScrollerY.mCurrVelocity; 438 if (Math.signum(velocityX) == Math.signum(oldVelocityX) && 439 Math.signum(velocityY) == Math.signum(oldVelocityY)) { 440 velocityX += oldVelocityX; 441 velocityY += oldVelocityY; 442 } 443 } 444 445 mMode = FLING_MODE; 446 mScrollerX.fling(startX, velocityX, minX, maxX, overX); 447 mScrollerY.fling(startY, velocityY, minY, maxY, overY); 448 } 449 450 /** 451 * Notify the scroller that we've reached a horizontal boundary. 452 * Normally the information to handle this will already be known 453 * when the animation is started, such as in a call to one of the 454 * fling functions. However there are cases where this cannot be known 455 * in advance. This function will transition the current motion and 456 * animate from startX to finalX as appropriate. 457 * 458 * @param startX Starting/current X position 459 * @param finalX Desired final X position 460 * @param overX Magnitude of overscroll allowed. This should be the maximum 461 * desired distance from finalX. Absolute value - must be positive. 462 */ 463 public void notifyHorizontalEdgeReached(int startX, int finalX, int overX) { 464 mScrollerX.notifyEdgeReached(startX, finalX, overX); 465 } 466 467 /** 468 * Notify the scroller that we've reached a vertical boundary. 469 * Normally the information to handle this will already be known 470 * when the animation is started, such as in a call to one of the 471 * fling functions. However there are cases where this cannot be known 472 * in advance. This function will animate a parabolic motion from 473 * startY to finalY. 474 * 475 * @param startY Starting/current Y position 476 * @param finalY Desired final Y position 477 * @param overY Magnitude of overscroll allowed. This should be the maximum 478 * desired distance from finalY. Absolute value - must be positive. 479 */ 480 public void notifyVerticalEdgeReached(int startY, int finalY, int overY) { 481 mScrollerY.notifyEdgeReached(startY, finalY, overY); 482 } 483 484 /** 485 * Returns whether the current Scroller is currently returning to a valid position. 486 * Valid bounds were provided by the 487 * {@link #fling(int, int, int, int, int, int, int, int, int, int)} method. 488 * 489 * One should check this value before calling 490 * {@link #startScroll(int, int, int, int)} as the interpolation currently in progress 491 * to restore a valid position will then be stopped. The caller has to take into account 492 * the fact that the started scroll will start from an overscrolled position. 493 * 494 * @return true when the current position is overscrolled and in the process of 495 * interpolating back to a valid value. 496 */ 497 public boolean isOverScrolled() { 498 return ((!mScrollerX.mFinished && 499 mScrollerX.mState != MagneticOverScroller.TO_EDGE) || 500 (!mScrollerY.mFinished && 501 mScrollerY.mState != MagneticOverScroller.TO_EDGE)); 502 } 503 504 /** 505 * Stops the animation. Contrary to {@link #forceFinished(boolean)}, 506 * aborting the animating causes the scroller to move to the final x and y 507 * positions. 508 * 509 * @see #forceFinished(boolean) 510 */ 511 public void abortAnimation() { 512 mScrollerX.finish(); 513 mScrollerY.finish(); 514 } 515 516 /** 517 * Returns the time elapsed since the beginning of the scrolling. 518 * 519 * @return The elapsed time in milliseconds. 520 * 521 * @hide 522 */ 523 public int timePassed() { 524 final long time = AnimationUtils.currentAnimationTimeMillis(); 525 final long startTime = Math.min(mScrollerX.mStartTime, mScrollerY.mStartTime); 526 return (int) (time - startTime); 527 } 528 529 /** 530 * @hide 531 */ 532 public boolean isScrollingInDirection(float xvel, float yvel) { 533 final int dx = mScrollerX.mFinal - mScrollerX.mStart; 534 final int dy = mScrollerY.mFinal - mScrollerY.mStart; 535 return !isFinished() && Math.signum(xvel) == Math.signum(dx) && 536 Math.signum(yvel) == Math.signum(dy); 537 } 538 539 class MagneticOverScroller { 540 // Initial position 541 int mStart; 542 543 // Current position 544 int mCurrentPosition; 545 546 // Final position 547 int mFinal; 548 549 // Initial velocity 550 int mVelocity; 551 552 // Current velocity 553 float mCurrVelocity; 554 555 // Constant current deceleration 556 float mDeceleration; 557 558 // Animation starting time, in system milliseconds 559 long mStartTime; 560 561 // Animation duration, in milliseconds 562 int mDuration; 563 564 // Duration to complete spline component of animation 565 int mSplineDuration; 566 567 // Distance to travel along spline animation 568 int mSplineDistance; 569 570 // Whether the animation is currently in progress 571 boolean mFinished; 572 573 private static final int TO_EDGE = 0; 574 private static final int TO_BOUNDARY = 1; 575 private static final int TO_BOUNCE = 2; 576 577 private int mState = TO_EDGE; 578 579 // The allowed overshot distance before boundary is reached. 580 private int mOver; 581 582 // If the velocity is smaller than this value, no bounce is triggered 583 // when the edge limits are reached (would result in a zero pixels 584 // displacement anyway). 585 private static final float MINIMUM_VELOCITY_FOR_BOUNCE = 140.0f; //Float.MAX_VALUE;//140.0f; 586 587 // Proportion of the velocity that is preserved when the edge is reached. 588 private static final float DEFAULT_BOUNCE_COEFFICIENT = 0.36f; 589 590 private float mBounceCoefficient = DEFAULT_BOUNCE_COEFFICIENT; 591 592 MagneticOverScroller() { 593 mFinished = true; 594 } 595 596 void updateScroll(float q) { 597 mCurrentPosition = mStart + Math.round(q * (mFinal - mStart)); 598 } 599 600 /* 601 * Get a signed deceleration that will reduce the velocity. 602 */ 603 float getDeceleration(int velocity) { 604 return velocity > 0 ? -OverScroller.this.mDeceleration : OverScroller.this.mDeceleration; 605 } 606 607 /* 608 * Modifies mDuration to the duration it takes to get from start to newFinal using the 609 * spline interpolation. The previous duration was needed to get to oldFinal. 610 */ 611 void adjustDuration(int start, int oldFinal, int newFinal) { 612 final int oldDistance = oldFinal - start; 613 final int newDistance = newFinal - start; 614 final float x = (float) Math.abs((float) newDistance / oldDistance); 615 final int index = (int) (NB_SAMPLES * x); 616 if (index < NB_SAMPLES) { 617 final float x_inf = (float) index / NB_SAMPLES; 618 final float x_sup = (float) (index + 1) / NB_SAMPLES; 619 final float t_inf = SPLINE_TIME[index]; 620 final float t_sup = SPLINE_TIME[index + 1]; 621 final float timeCoef = t_inf + (x - x_inf) / (x_sup - x_inf) * (t_sup - t_inf); 622 623 mDuration *= timeCoef; 624 } 625 } 626 627 void startScroll(int start, int distance, int duration) { 628 mFinished = false; 629 630 mStart = start; 631 mFinal = start + distance; 632 633 mStartTime = AnimationUtils.currentAnimationTimeMillis(); 634 mDuration = duration; 635 636 // Unused 637 mDeceleration = 0.0f; 638 mVelocity = 0; 639 } 640 641 void finish() { 642 mCurrentPosition = mFinal; 643 // Not reset since WebView relies on this value for fast fling. 644 // TODO: restore when WebView uses the fast fling implemented in this class. 645 // mCurrVelocity = 0.0f; 646 mFinished = true; 647 } 648 649 void setFinalPosition(int position) { 650 mFinal = position; 651 mFinished = false; 652 } 653 654 void extendDuration(int extend) { 655 final long time = AnimationUtils.currentAnimationTimeMillis(); 656 final int elapsedTime = (int) (time - mStartTime); 657 mDuration = elapsedTime + extend; 658 mFinished = false; 659 } 660 661 void setBounceCoefficient(float coefficient) { 662 mBounceCoefficient = coefficient; 663 } 664 665 boolean springback(int start, int min, int max) { 666 mFinished = true; 667 668 mStart = mFinal = start; 669 mVelocity = 0; 670 671 mStartTime = AnimationUtils.currentAnimationTimeMillis(); 672 mDuration = 0; 673 674 if (start < min) { 675 startSpringback(start, min, 0); 676 } else if (start > max) { 677 startSpringback(start, max, 0); 678 } 679 680 return !mFinished; 681 } 682 683 private void startSpringback(int start, int end, int velocity) { 684 mFinished = false; 685 mState = TO_BOUNCE; 686 mStart = mFinal = end; 687 final float velocitySign = Math.signum(start - end); 688 mDeceleration = getDeceleration((int) velocitySign); 689 fitOnBounceCurve(start, end, velocity); 690 mDuration = - (int) (2000.0f * mVelocity / mDeceleration); 691 } 692 693 void fling(int start, int velocity, int min, int max, int over) { 694 mOver = over; 695 mFinished = false; 696 mCurrVelocity = mVelocity = velocity; 697 mDuration = mSplineDuration = 0; 698 mStartTime = AnimationUtils.currentAnimationTimeMillis(); 699 mStart = start; 700 701 if (start > max || start < min) { 702 startAfterEdge(start, min, max, velocity); 703 return; 704 } 705 706 mState = TO_EDGE; 707 double totalDistance = 0.0; 708 709 if (velocity != 0) { 710 final double l = Math.log(START_TENSION * Math.abs(velocity) / ALPHA); 711 // Duration are expressed in milliseconds 712 mDuration = mSplineDuration = (int) (1000.0 * Math.exp(l / (DECELERATION_RATE - 1.0))); 713 totalDistance = (ALPHA * Math.exp(DECELERATION_RATE / (DECELERATION_RATE - 1.0) * l)); 714 } 715 716 mSplineDistance = (int) (totalDistance * Math.signum(velocity)); 717 mFinal = start + mSplineDistance; 718 719 // Clamp to a valid final position 720 if (mFinal < min) { 721 adjustDuration(mStart, mFinal, min); 722 mFinal = min; 723 } 724 725 if (mFinal > max) { 726 adjustDuration(mStart, mFinal, max); 727 mFinal = max; 728 } 729 } 730 731 private void fitOnBounceCurve(int start, int end, int velocity) { 732 // Simulate a bounce that started from edge 733 final float durationToApex = - velocity / mDeceleration; 734 final float distanceToApex = velocity * velocity / 2.0f / Math.abs(mDeceleration); 735 final float distanceToEdge = Math.abs(end - start); 736 final float totalDuration = (float) Math.sqrt( 737 2.0 * (distanceToApex + distanceToEdge) / Math.abs(mDeceleration)); 738 mStartTime -= (int) (1000.0f * (totalDuration - durationToApex)); 739 mStart = end; 740 mVelocity = (int) (- mDeceleration * totalDuration); 741 } 742 743 private void startBounceAfterEdge(int start, int end, int velocity) { 744 mDeceleration = getDeceleration(velocity == 0 ? start - end : velocity); 745 fitOnBounceCurve(start, end, velocity); 746 onEdgeReached(); 747 } 748 749 private void startAfterEdge(int start, int min, int max, int velocity) { 750 if (start > min && start < max) { 751 mFinished = true; 752 return; 753 } 754 final boolean positive = start > max; 755 final int edge = positive ? max : min; 756 final int overDistance = start - edge; 757 boolean keepIncreasing = overDistance * velocity >= 0; 758 if (keepIncreasing) { 759 // Will result in a bounce or a to_boundary depending on velocity. 760 startBounceAfterEdge(start, edge, velocity); 761 } else { 762 final double l = Math.log(START_TENSION * Math.abs(velocity) / ALPHA); 763 final double totalDistance = 764 (ALPHA * Math.exp(DECELERATION_RATE / (DECELERATION_RATE - 1.0) * l)); 765 if (totalDistance > Math.abs(overDistance)) { 766 fling(start, velocity, positive ? min : start, positive ? start : max, mOver); 767 } else { 768 startSpringback(start, edge, velocity); 769 } 770 } 771 } 772 773 void notifyEdgeReached(int start, int end, int over) { 774 mOver = over; 775 mStartTime = AnimationUtils.currentAnimationTimeMillis(); 776 // We were in fling/scroll mode before: current velocity is such that distance to edge 777 // is increasing. Ensures that startAfterEdge will not start a new fling. 778 startAfterEdge(start, end, end, (int) mCurrVelocity); 779 } 780 781 private void onEdgeReached() { 782 // mStart, mVelocity and mStartTime were adjusted to their values when edge was reached. 783 final float distance = - mVelocity * mVelocity / (2.0f * mDeceleration); 784 785 if (Math.abs(distance) < mOver) { 786 // Spring force will bring us back to final position 787 mState = TO_BOUNCE; 788 mFinal = mStart; 789 mDuration = - (int) (2000.0f * mVelocity / mDeceleration); 790 } else { 791 // Velocity is too high, we will hit the boundary limit 792 mState = TO_BOUNDARY; 793 int over = mVelocity > 0 ? mOver : -mOver; 794 mFinal = mStart + over; 795 mDuration = (int) (1000.0 * Math.PI * over / 2.0 / mVelocity); 796 } 797 } 798 799 boolean continueWhenFinished() { 800 switch (mState) { 801 case TO_EDGE: 802 // Duration from start to null velocity 803 if (mDuration < mSplineDuration) { 804 // If the animation was clamped, we reached the edge 805 mStart = mFinal; 806 // Speed when edge was reached 807 mVelocity = (int) mCurrVelocity; 808 mDeceleration = getDeceleration(mVelocity); 809 mStartTime += mDuration; 810 onEdgeReached(); 811 } else { 812 // Normal stop, no need to continue 813 return false; 814 } 815 break; 816 case TO_BOUNDARY: 817 mStartTime += mDuration; 818 startSpringback(mFinal, mFinal - (mVelocity > 0 ? mOver:-mOver), 0); 819 break; 820 case TO_BOUNCE: 821 mVelocity = (int) (mVelocity * mBounceCoefficient); 822 if (Math.abs(mVelocity) < MINIMUM_VELOCITY_FOR_BOUNCE) { 823 return false; 824 } 825 mStartTime += mDuration; 826 mDuration = - (int) (mVelocity / mDeceleration); 827 break; 828 } 829 830 update(); 831 return true; 832 } 833 834 /* 835 * Update the current position and velocity for current time. Returns 836 * true if update has been done and false if animation duration has been 837 * reached. 838 */ 839 boolean update() { 840 final long time = AnimationUtils.currentAnimationTimeMillis(); 841 final long currentTime = time - mStartTime; 842 843 if (currentTime > mDuration) { 844 return false; 845 } 846 847 double distance = 0.0; 848 switch (mState) { 849 case TO_EDGE: { 850 final float t = (float) currentTime / mSplineDuration; 851 final int index = (int) (NB_SAMPLES * t); 852 float distanceCoef = 1.f; 853 float velocityCoef = 0.f; 854 if (index < NB_SAMPLES) { 855 final float t_inf = (float) index / NB_SAMPLES; 856 final float t_sup = (float) (index + 1) / NB_SAMPLES; 857 final float d_inf = SPLINE_POSITION[index]; 858 final float d_sup = SPLINE_POSITION[index + 1]; 859 velocityCoef = (d_sup - d_inf) / (t_sup - t_inf); 860 distanceCoef = d_inf + (t - t_inf) * velocityCoef; 861 } 862 863 distance = distanceCoef * mSplineDistance; 864 mCurrVelocity = velocityCoef * mSplineDistance / mSplineDuration * 1000; 865 break; 866 } 867 868 case TO_BOUNCE: { 869 final float t = currentTime / 1000.0f; 870 mCurrVelocity = mVelocity + mDeceleration * t; 871 distance = mVelocity * t + mDeceleration * t * t / 2.0f; 872 break; 873 } 874 875 case TO_BOUNDARY: { 876 final float t = currentTime / 1000.0f; 877 final float d = t * Math.abs(mVelocity) / mOver; 878 mCurrVelocity = mVelocity * (float) Math.cos(d); 879 distance = (mVelocity > 0 ? mOver : -mOver) * Math.sin(d); 880 break; 881 } 882 } 883 884 mCurrentPosition = mStart + (int) Math.round(distance); 885 return true; 886 } 887 } 888} 889