滚动手势动画

编写:Andrwyw - 原文:http://developer.android.com/training/gestures/scroll.html

在Android中,通常使用ScrollView类来实现滚动(scroll)。任何可能超过父类边界的布局,都应该嵌套在ScrollView中,来提供一个由系统框架管理的可滚动的view。仅在某些特殊情形下,我们才要实现一个自定义scroller。本节课程就描述了这样一个情形:使用 scrollers 显示滚动效果,以响应触摸手势。

为了收集数据来产生滚动动画,以响应一个触摸事件,我们可以使用scrollers(Scroller或者OverScroller)。这两个类很相似,但OverScroller有一些函数,能在平移或快速滑动手势后,向用户指出已经达到内容的边缘。InteractiveChart 例子使用了EdgeEffect类(实际上是EdgeEffectCompat类),在用户到达内容的边缘时显示“发光”效果。

Note: 比起Scroller类,我们更推荐使用OverScroller类来产生滚动动画。OverScroller类为老设备提供了很好的向后兼容性。 另外需要注意的是,仅当我们要自己实现滚动时,才需要使用scrollers。如果我们把布局嵌套在ScrollViewHorizontalScrollView中,它们会帮我们把这些做好。

通过使用平台标准的滚动物理因素(摩擦、速度等),scroller被用来随着时间的推移产生滚动动画。实际上,scroller本身不会绘制任何东西。Scrollers只是随着时间的推移,追踪滚动的偏移量,但它们不会自动地把这些位置应用到view上。我们应该按一定频率,获取并应用这些新的坐标值,来让滚动动画更加顺滑。

理解滚动术语

在Android中,“Scrolling”这个词根据不同情景有着不同的含义。

滚动(Scrolling)是指移动视窗(viewport)(指你正在看的内容所在的‘窗口’)的一般过程。当在x轴和y轴方向同时滚动时,就叫做平移panning)。示例程序提供的 InteractiveChart 类,展示了两种不同类型的滚动,拖拽与快速滑动。

  • 拖拽(dragging)是滚动的一种类型,当用户在触摸屏上拖动手指时发生。简单的拖拽一般可以通过重写 GestureDetector.OnGestureListeneronScroll() 来实现。关于拖拽的更多讨论,可以查看拖拽与缩放章节。
  • 快速滑动(fling)这种类型的滚动,在用户快速拖拽后,抬起手指时发生。当用户抬起手指后,我们通常想继续保持滚动(移动视窗),但会一直减速直到视窗停止移动。通过重写GestureDetector.OnGestureListeneronFling()函数,使用scroller对象,可实现快速滑动。这种用法也就是本节课程的主题。

scroller对象通常会与快速滑动手势结合起来使用。但在任何我们想让UI展示滚动动画,以响应触摸事件的场景,都可以用scroller对象来实现。比如,我们可以重写onTouchEvent()函数,直接处理触摸事件,并且产生一个滚动效果或“页面对齐”动画(snapping to page),来响应这些触摸事件。

实现基于触摸的滚动

本节讲述如何使用scroller。下面的代码段来自 InteractiveChart 示例。它使用GestureDetector,并且重写了GestureDetector.SimpleOnGestureListeneronFling() 函数。它使用OverScroller追踪快速滑动(fling)手势。快速滑动手势后,如果用户到达内容边缘,应用会显示一种发光效果。

Note: InteractiveChart示例程序展示了一个可缩放、平移、滑动的表格。在接下来的代码段中,mContentRect表示view中的一块矩形坐标区域,该区域将被用来绘制表格。在任意给定的时间点,表格中某一部分会被绘制在这个区域内。mCurrentViewport表示当前在屏幕上可见的那一部分表格。因为像素偏移量通常当作整型处理,所以mContentRectRect类型的。因为图表的区域范围是数值型/浮点型值,所以mCurrentViewportRectF类型。

代码段的第一部分展示了onFling()函数的实现:

  1. // The current viewport. This rectangle represents the currently visible
  2. // chart domain and range. The viewport is the part of the app that the
  3. // user manipulates via touch gestures.
  4. private RectF mCurrentViewport =
  5. new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX);
  6. // The current destination rectangle (in pixel coordinates) into which the
  7. // chart data should be drawn.
  8. private Rect mContentRect;
  9. private OverScroller mScroller;
  10. private RectF mScrollerStartViewport;
  11. ...
  12. private final GestureDetector.SimpleOnGestureListener mGestureListener
  13. = new GestureDetector.SimpleOnGestureListener() {
  14. @Override
  15. public boolean onDown(MotionEvent e) {
  16. // Initiates the decay phase of any active edge effects.
  17. releaseEdgeEffects();
  18. mScrollerStartViewport.set(mCurrentViewport);
  19. // Aborts any active scroll animations and invalidates.
  20. mScroller.forceFinished(true);
  21. ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this);
  22. return true;
  23. }
  24. ...
  25. @Override
  26. public boolean onFling(MotionEvent e1, MotionEvent e2,
  27. float velocityX, float velocityY) {
  28. fling((int) -velocityX, (int) -velocityY);
  29. return true;
  30. }
  31. };
  32. private void fling(int velocityX, int velocityY) {
  33. // Initiates the decay phase of any active edge effects.
  34. releaseEdgeEffects();
  35. // Flings use math in pixels (as opposed to math based on the viewport).
  36. Point surfaceSize = computeScrollSurfaceSize();
  37. mScrollerStartViewport.set(mCurrentViewport);
  38. int startX = (int) (surfaceSize.x * (mScrollerStartViewport.left -
  39. AXIS_X_MIN) / (
  40. AXIS_X_MAX - AXIS_X_MIN));
  41. int startY = (int) (surfaceSize.y * (AXIS_Y_MAX -
  42. mScrollerStartViewport.bottom) / (
  43. AXIS_Y_MAX - AXIS_Y_MIN));
  44. // Before flinging, aborts the current animation.
  45. mScroller.forceFinished(true);
  46. // Begins the animation
  47. mScroller.fling(
  48. // Current scroll position
  49. startX,
  50. startY,
  51. velocityX,
  52. velocityY,
  53. /*
  54. * Minimum and maximum scroll positions. The minimum scroll
  55. * position is generally zero and the maximum scroll position
  56. * is generally the content size less the screen size. So if the
  57. * content width is 1000 pixels and the screen width is 200
  58. * pixels, the maximum scroll offset should be 800 pixels.
  59. */
  60. 0, surfaceSize.x - mContentRect.width(),
  61. 0, surfaceSize.y - mContentRect.height(),
  62. // The edges of the content. This comes into play when using
  63. // the EdgeEffect class to draw "glow" overlays.
  64. mContentRect.width() / 2,
  65. mContentRect.height() / 2);
  66. // Invalidates to trigger computeScroll()
  67. ViewCompat.postInvalidateOnAnimation(this);
  68. }

onFling()函数调用postInvalidateOnAnimation()时,它会触发computeScroll()来更新x、y的值。通常一个子view用scroller对象来产生滚动动画时会这样做,就像本例一样。

大多数views直接通过scrollTo()函数传递scroller对象的x、y坐标值。接下来的computeScroll()函数的实现中采用了一种不同的方式。它调用computeScrollOffset()函数来获得当前位置的x、y值。当满足边缘显示发光效果的条件时(图表已被放大显示,x或y值超过边界,并且app当前没有显示overscroll),这段代码会设置overscroll发光效果,并调用postInvalidateOnAnimation()函数来让view失效重绘:

  1. // Edge effect / overscroll tracking objects.
  2. private EdgeEffectCompat mEdgeEffectTop;
  3. private EdgeEffectCompat mEdgeEffectBottom;
  4. private EdgeEffectCompat mEdgeEffectLeft;
  5. private EdgeEffectCompat mEdgeEffectRight;
  6. private boolean mEdgeEffectTopActive;
  7. private boolean mEdgeEffectBottomActive;
  8. private boolean mEdgeEffectLeftActive;
  9. private boolean mEdgeEffectRightActive;
  10. @Override
  11. public void computeScroll() {
  12. super.computeScroll();
  13. boolean needsInvalidate = false;
  14. // The scroller isn't finished, meaning a fling or programmatic pan
  15. // operation is currently active.
  16. if (mScroller.computeScrollOffset()) {
  17. Point surfaceSize = computeScrollSurfaceSize();
  18. int currX = mScroller.getCurrX();
  19. int currY = mScroller.getCurrY();
  20. boolean canScrollX = (mCurrentViewport.left > AXIS_X_MIN
  21. || mCurrentViewport.right < AXIS_X_MAX);
  22. boolean canScrollY = (mCurrentViewport.top > AXIS_Y_MIN
  23. || mCurrentViewport.bottom < AXIS_Y_MAX);
  24. /*
  25. * If you are zoomed in and currX or currY is
  26. * outside of bounds and you're not already
  27. * showing overscroll, then render the overscroll
  28. * glow edge effect.
  29. */
  30. if (canScrollX
  31. && currX < 0
  32. && mEdgeEffectLeft.isFinished()
  33. && !mEdgeEffectLeftActive) {
  34. mEdgeEffectLeft.onAbsorb((int)
  35. OverScrollerCompat.getCurrVelocity(mScroller));
  36. mEdgeEffectLeftActive = true;
  37. needsInvalidate = true;
  38. } else if (canScrollX
  39. && currX > (surfaceSize.x - mContentRect.width())
  40. && mEdgeEffectRight.isFinished()
  41. && !mEdgeEffectRightActive) {
  42. mEdgeEffectRight.onAbsorb((int)
  43. OverScrollerCompat.getCurrVelocity(mScroller));
  44. mEdgeEffectRightActive = true;
  45. needsInvalidate = true;
  46. }
  47. if (canScrollY
  48. && currY < 0
  49. && mEdgeEffectTop.isFinished()
  50. && !mEdgeEffectTopActive) {
  51. mEdgeEffectTop.onAbsorb((int)
  52. OverScrollerCompat.getCurrVelocity(mScroller));
  53. mEdgeEffectTopActive = true;
  54. needsInvalidate = true;
  55. } else if (canScrollY
  56. && currY > (surfaceSize.y - mContentRect.height())
  57. && mEdgeEffectBottom.isFinished()
  58. && !mEdgeEffectBottomActive) {
  59. mEdgeEffectBottom.onAbsorb((int)
  60. OverScrollerCompat.getCurrVelocity(mScroller));
  61. mEdgeEffectBottomActive = true;
  62. needsInvalidate = true;
  63. }
  64. ...
  65. }

这是缩放部分的代码:

  1. // Custom object that is functionally similar to Scroller
  2. Zoomer mZoomer;
  3. private PointF mZoomFocalPoint = new PointF();
  4. ...
  5. // If a zoom is in progress (either programmatically or via double
  6. // touch), performs the zoom.
  7. if (mZoomer.computeZoom()) {
  8. float newWidth = (1f - mZoomer.getCurrZoom()) *
  9. mScrollerStartViewport.width();
  10. float newHeight = (1f - mZoomer.getCurrZoom()) *
  11. mScrollerStartViewport.height();
  12. float pointWithinViewportX = (mZoomFocalPoint.x -
  13. mScrollerStartViewport.left)
  14. / mScrollerStartViewport.width();
  15. float pointWithinViewportY = (mZoomFocalPoint.y -
  16. mScrollerStartViewport.top)
  17. / mScrollerStartViewport.height();
  18. mCurrentViewport.set(
  19. mZoomFocalPoint.x - newWidth * pointWithinViewportX,
  20. mZoomFocalPoint.y - newHeight * pointWithinViewportY,
  21. mZoomFocalPoint.x + newWidth * (1 - pointWithinViewportX),
  22. mZoomFocalPoint.y + newHeight * (1 - pointWithinViewportY));
  23. constrainViewport();
  24. needsInvalidate = true;
  25. }
  26. if (needsInvalidate) {
  27. ViewCompat.postInvalidateOnAnimation(this);
  28. }

这是上面代码段中调用过的computeScrollSurfaceSize()函数。它会以像素为单位计算当前可滚动的尺寸。举例来说,如果整个图表区域都是可见的,它的值就简单地等于mContentRect的大小。如果图表在两个方向上都放大到200%,此函数返回的尺寸在水平、垂直方向上都会大两倍。

  1. private Point computeScrollSurfaceSize() {
  2. return new Point(
  3. (int) (mContentRect.width() * (AXIS_X_MAX - AXIS_X_MIN)
  4. / mCurrentViewport.width()),
  5. (int) (mContentRect.height() * (AXIS_Y_MAX - AXIS_Y_MIN)
  6. / mCurrentViewport.height()));
  7. }

关于scroller用法的另一个示例,可查看ViewPager类的源代码。它用滚动来响应快速滑动(fling),并且使用滚动来实现“页面对齐”(snapping to page)动画。