手势识别官方教程(4)在挑划或拖动手势后view的滚动用ScrollView和 HorizontalScrollView,自定义用Scroller或OverScroller
简单滚动用ScrollView和 HorizontalScrollView就够。自定义view时可能要自定义滚动效果,可以使用 Scroller或 OverScroller
Animating a Scroll Gesture
In Android, scrolling is typically achieved by using the ScrollView
class. Any standard layout that might extend beyond the bounds of its container should be nested in a ScrollView
to provide a scrollable view that's managed by the framework. Implementing a custom scroller should only be necessary for special scenarios. This lesson describes such a scenario: displaying a scrolling effect in response to touch gestures using scrollers.
You can use scrollers (Scroller
or OverScroller
) to collect the data you need to produce a scrolling animation in response to a touch event. They are similar, but OverScroller
includes methods for indicating to users that they've reached the content edges after a pan or fling gesture.
OverScroller包含滚动到边时的动画,而 Scroller 没有,推荐使用 OverScroller
The InteractiveChart
sample uses the EdgeEffect
class (actually the EdgeEffectCompat
class) to display a "glow" effect when users reach the content edges.
Note: We recommend that you use OverScroller
rather than Scroller
for scrolling animations. OverScroller
provides the best backward compatibility with older devices.
Also note that you generally only need to use scrollers when implementing scrolling yourself. ScrollView
and HorizontalScrollView
do all of this for you if you nest your layout within them.
通常如果只要简单滚动效果,那么 ScrollView 和 HorizontalScrollView 就够用了。
A scroller is used to animate scrolling over time, using platform-standard scrolling physics (friction, velocity, etc.). The scroller itself doesn't actually draw anything. Scrollers track scroll offsets for you over time, but they don't automatically apply those positions to your view. It's your responsibility to get and apply new coordinates at a rate that will make the scrolling animation look smooth.
滚动器只负责根据速度,摩擦等记录滚动的偏移量,并不绘制,绘制和刷新坐标是使用者的责任。
Understand Scrolling Terminology (滚动的定义)
"Scrolling" is a word that can take on different meanings in Android, depending on the context.
Scrolling is the general process of moving the viewport (that is, the 'window' of content you're looking at). When scrolling is in both the x and y axes, it's called panning. The sample application provided with this class,InteractiveChart
, illustrates two different types of scrolling, dragging and flinging:
滚动的定义在不同上下文中,含义不同,但都是在其它手势之后才产生。如下:
- Dragging is the type of scrolling that occurs when a user drags her finger across the touch screen. Simple dragging is often implemented by overriding
onScroll()
inGestureDetector.OnGestureListener
. For more discussion of dragging, see Dragging and Scaling.在拖拽手势后:分按住一点一起拖动直到停止才松手,GestureDetector.OnGestureListener的onScroll()中处理 。
- Flinging is the type of scrolling that occurs when a user drags and lifts her finger quickly. After the user lifts her finger, you generally want to keep scrolling (moving the viewport), but decelerate until the viewport stops moving. Flinging can be implemented by overriding
onFling()
inGestureDetector.OnGestureListener
, and by using a scroller object. This is the use case that is the topic of this lesson.在挑划手势后:按住一点划下就松手,GestureDetector.OnGestureListener的onFling()中处理。
It's common to use scroller objects in conjunction with a fling gesture, but they can be used in pretty much any context where you want the UI to display scrolling in response to a touch event. For example, you could override onTouchEvent()
to process touch events directly, and produce a scrolling effect or a "snapping to page" animation in response to those touch events.
Implement Touch-Based Scrolling
This section describes how to use a scroller. The snippet shown below comes from the InteractiveChart
sample provided with this class. It uses a GestureDetector
, and overrides the GestureDetector.SimpleOnGestureListener
method onFling()
. It uses OverScroller
to track the fling gesture. If the user reaches the content edges after the fling gesture, the app displays a "glow" effect.
Note: The InteractiveChart
sample app displays a chart that you can zoom, pan, scroll, and so on. In the following snippet, mContentRect
represents the rectangle coordinates within the view that the chart will be drawn into. At any given time, a subset of the total chart domain and range are drawn into this rectangular area. mCurrentViewport
represents the portion of the chart that is currently visible in the screen. Because pixel offsets are generally treated as integers, mContentRect
is of the type Rect
. Because the graph domain and range are decimal/float values, mCurrentViewport
is of the type RectF
.
The first part of the snippet shows the implementation of onFling()
:
下面是一个在挑划手势后有动画的滚动处理示例(OverScroller)
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 7 // The current destination rectangle (in pixel coordinates) into which the 8 // chart data should be drawn. 9 private Rect mContentRect; 10 11 private OverScroller mScroller; 12 private RectF mScrollerStartViewport; 13 ... 14 private final GestureDetector.SimpleOnGestureListener mGestureListener 15 = new GestureDetector.SimpleOnGestureListener() { 16 @Override 17 public boolean onDown(MotionEvent e) { 18 // Initiates the decay phase of any active edge effects. 19 releaseEdgeEffects(); 20 mScrollerStartViewport.set(mCurrentViewport); 21 // Aborts any active scroll animations and invalidates. 22 mScroller.forceFinished(true); 23 ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this); 24 return true; 25 } 26 ... 27 @Override 28 public boolean onFling(MotionEvent e1, MotionEvent e2, 29 float velocityX, float velocityY) { 30 fling((int) -velocityX, (int) -velocityY); 31 return true; 32 } 33 }; 34 35 private void fling(int velocityX, int velocityY) { 36 // Initiates the decay phase of any active edge effects. 37 releaseEdgeEffects(); 38 // Flings use math in pixels (as opposed to math based on the viewport). 39 Point surfaceSize = computeScrollSurfaceSize(); 40 mScrollerStartViewport.set(mCurrentViewport); 41 int startX = (int) (surfaceSize.x * (mScrollerStartViewport.left - 42 AXIS_X_MIN) / ( 43 AXIS_X_MAX - AXIS_X_MIN)); 44 int startY = (int) (surfaceSize.y * (AXIS_Y_MAX - 45 mScrollerStartViewport.bottom) / ( 46 AXIS_Y_MAX - AXIS_Y_MIN)); 47 // Before flinging, aborts the current animation. 48 mScroller.forceFinished(true); 49 // Begins the animation 50 mScroller.fling( 51 // Current scroll position 52 startX, 53 startY, 54 velocityX, 55 velocityY, 56 /* 57 * Minimum and maximum scroll positions. The minimum scroll 58 * position is generally zero and the maximum scroll position 59 * is generally the content size less the screen size. So if the 60 * content width is 1000 pixels and the screen width is 200 61 * pixels, the maximum scroll offset should be 800 pixels. 62 */ 63 0, surfaceSize.x - mContentRect.width(), 64 0, surfaceSize.y - mContentRect.height(), 65 // The edges of the content. This comes into play when using 66 // the EdgeEffect class to draw "glow" overlays. 67 mContentRect.width() / 2, 68 mContentRect.height() / 2); 69 // Invalidates to trigger computeScroll() 70 ViewCompat.postInvalidateOnAnimation(this); 71 }
When onFling()
calls postInvalidateOnAnimation()
, it triggers computeScroll()
to update the values for x and y. This is typically be done when a view child is animating a scroll using a scroller object, as in this example.
Most views pass the scroller object's x and y position directly to scrollTo()
. The following implementation of computeScroll()
takes a different approach—it calls computeScrollOffset()
to get the current location of x and y. When the criteria for displaying an overscroll "glow" edge effect are met (the display is zoomed in, x or y is out of bounds, and the app isn't already showing an overscroll), the code sets up the overscroll glow effect and calls postInvalidateOnAnimation()
to trigger an invalidate on the view:
1 // Edge effect / overscroll tracking objects. 2 private EdgeEffectCompat mEdgeEffectTop; 3 private EdgeEffectCompat mEdgeEffectBottom; 4 private EdgeEffectCompat mEdgeEffectLeft; 5 private EdgeEffectCompat mEdgeEffectRight; 6 7 private boolean mEdgeEffectTopActive; 8 private boolean mEdgeEffectBottomActive; 9 private boolean mEdgeEffectLeftActive; 10 private boolean mEdgeEffectRightActive; 11 12 @Override 13 public void computeScroll() { 14 super.computeScroll(); 15 16 boolean needsInvalidate = false; 17 18 // The scroller isn't finished, meaning a fling or programmatic pan 19 // operation is currently active. 20 if (mScroller.computeScrollOffset()) { 21 Point surfaceSize = computeScrollSurfaceSize(); 22 int currX = mScroller.getCurrX(); 23 int currY = mScroller.getCurrY(); 24 25 boolean canScrollX = (mCurrentViewport.left > AXIS_X_MIN 26 || mCurrentViewport.right < AXIS_X_MAX); 27 boolean canScrollY = (mCurrentViewport.top > AXIS_Y_MIN 28 || mCurrentViewport.bottom < AXIS_Y_MAX); 29 30 /* 31 * If you are zoomed in and currX or currY is 32 * outside of bounds and you're not already 33 * showing overscroll, then render the overscroll 34 * glow edge effect. 35 */ 36 if (canScrollX 37 && currX < 0 38 && mEdgeEffectLeft.isFinished() 39 && !mEdgeEffectLeftActive) { 40 mEdgeEffectLeft.onAbsorb((int) 41 OverScrollerCompat.getCurrVelocity(mScroller)); 42 mEdgeEffectLeftActive = true; 43 needsInvalidate = true; 44 } else if (canScrollX 45 && currX > (surfaceSize.x - mContentRect.width()) 46 && mEdgeEffectRight.isFinished() 47 && !mEdgeEffectRightActive) { 48 mEdgeEffectRight.onAbsorb((int) 49 OverScrollerCompat.getCurrVelocity(mScroller)); 50 mEdgeEffectRightActive = true; 51 needsInvalidate = true; 52 } 53 54 if (canScrollY 55 && currY < 0 56 && mEdgeEffectTop.isFinished() 57 && !mEdgeEffectTopActive) { 58 mEdgeEffectTop.onAbsorb((int) 59 OverScrollerCompat.getCurrVelocity(mScroller)); 60 mEdgeEffectTopActive = true; 61 needsInvalidate = true; 62 } else if (canScrollY 63 && currY > (surfaceSize.y - mContentRect.height()) 64 && mEdgeEffectBottom.isFinished() 65 && !mEdgeEffectBottomActive) { 66 mEdgeEffectBottom.onAbsorb((int) 67 OverScrollerCompat.getCurrVelocity(mScroller)); 68 mEdgeEffectBottomActive = true; 69 needsInvalidate = true; 70 } 71 ... 72 }
Here is the section of the code that performs the actual zoom:
1 // Custom object that is functionally similar to Scroller 2 Zoomer mZoomer; 3 private PointF mZoomFocalPoint = new PointF(); 4 ... 5 6 // If a zoom is in progress (either programmatically or via double 7 // touch), performs the zoom. 8 if (mZoomer.computeZoom()) { 9 float newWidth = (1f - mZoomer.getCurrZoom()) * 10 mScrollerStartViewport.width(); 11 float newHeight = (1f - mZoomer.getCurrZoom()) * 12 mScrollerStartViewport.height(); 13 float pointWithinViewportX = (mZoomFocalPoint.x - 14 mScrollerStartViewport.left) 15 / mScrollerStartViewport.width(); 16 float pointWithinViewportY = (mZoomFocalPoint.y - 17 mScrollerStartViewport.top) 18 / mScrollerStartViewport.height(); 19 mCurrentViewport.set( 20 mZoomFocalPoint.x - newWidth * pointWithinViewportX, 21 mZoomFocalPoint.y - newHeight * pointWithinViewportY, 22 mZoomFocalPoint.x + newWidth * (1 - pointWithinViewportX), 23 mZoomFocalPoint.y + newHeight * (1 - pointWithinViewportY)); 24 constrainViewport(); 25 needsInvalidate = true; 26 } 27 if (needsInvalidate) { 28 ViewCompat.postInvalidateOnAnimation(this); 29 }
This is the computeScrollSurfaceSize()
method that's called in the above snippet. It computes the current scrollable surface size, in pixels. For example, if the entire chart area is visible, this is simply the current size of mContentRect
. If the chart is zoomed in 200% in both directions, the returned size will be twice as large horizontally and vertically.
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 }
For another example of scroller usage, see the source code for the ViewPager
class. It scrolls in response to flings, and uses scrolling to implement the "snapping to page" animation.