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