標籤:
原文地址:http://android.xsoftlab.net/training/gestures/scroll.html
在Android中,滑動經常由ScrollView類來實現。任何超出容器邊界的布局都應該將自己內嵌在ScrollView中,以便提供可滾動的視圖效果。自訂滾動只有在特定的情境下才會被用到。這節課將會描述這樣一種情境:使用scroller顯示一種可滾動的效果。
你可以使用Scroller或者OverScroller來收集一些滑動動畫所需要的資料。這兩個類很相似,但是OverScroller包含了一些用於指示已經到達布局邊界的方法。樣本InteractiveChart在這裡使用了類EdgeEffect(實際上是類EdgeEffectCompat),在使用者到達布局邊界時會顯示一種”glow“的效果。
Note: 我們推薦使用OverScroller。這個類提供了良好的向後相容性。還應該注意,通常只有在實現滑動自己內部的時候,才需要使用到scroller類。如果你將布局嵌入到ScrollView或HorizontalScrollView中的話,那麼它們會將滾動的相關事宜做好。
Scroller用於在時間軸上做動畫滾動效果,它使用了標準的滾動物理學(摩擦力、速度等等)。Scroller本身不會繪製任何東西。Scroller會隨著時間的變化追蹤移動的位移量,但是它們不會自動的將這些值應用在你的View上。你需要自己擷取這些值並使用,這樣才會使滑動的效果更流暢。
瞭解滑動術語
“Scrolling”這個詞在Android中可被翻譯為各種不同的意思,這取決於具體的上下文。
Scrolling是一種viewport(viewport的意思是,你所看到的內容的視窗)移動的通用處理過程。當scrolling處於x軸及y軸上時,這被稱為“平移(panning)”。樣本程式提供了相關的類:InteractiveChart,示範了滑動的兩種不同類型,dragging(拖動)及flinging(滑動):
- Dragging 該滾動類型在這種情況下發生:當使用者的手指在螢幕上來回滑動時。簡單的Dragging由GestureDetector.OnGestureListener介面的onScroll()方法實現。
- Flinging 該滾動類型在這種情況下發生:當使用者快速在螢幕上滑動並離開螢幕時。在使用者離開了螢幕之後,常理上應該保持滾動狀態,並隨之慢慢減速,直到viewport停止移動。Flinging由GestureDetector.OnGestureListener介面的onFling()方法及scroller對象所實現。
將scroller對象與滑動手勢結合使用是一種共通的方法。你可以重寫onTouchEvent()方法直接處理觸摸事件,並降低滑動的速度來響應相應的觸摸事件。
實現基礎滾動
這部分章節將會描述如何使用scroller。下面的程式碼片段摘自樣本應用InteractiveChart。它在這裡使用了一個GestureDetector對象,重寫了GestureDetector.SimpleOnGestureListener的onFling()方法。它使用了OverScroller來追蹤滑動中的手勢。如果使用者在滑動之後到達了內容的邊緣,那麼APP會顯示一個”glow”的效果。
Note: 樣本APP InteractiveChart 展示了一個圖表,這個表徵圖可以縮放、平移、滾動等等。在下面的程式碼片段中,mContentRect代表了矩形的座標點,而繪製圖表的View則居於其中。在給定的時間內,一個總表的子集將會被繪製到這塊地區內。mCurrentViewport代表了螢幕中當前可視的部分圖表。因為像素的位移量通常被當做整型,所以mContentRect的類型是Rect。因為圖形的資料範圍是小數類型,所以mCurrentViewport的類型是RectF。
程式碼片段的第一部分展示了onFling()方法的實現:
// The current viewport. This rectangle represents the currently visible // chart domain and range. The viewport is the part of the app that the// user manipulates via touch gestures.private RectF mCurrentViewport = new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX);// The current destination rectangle (in pixel coordinates) into which the // chart data should be drawn.private Rect mContentRect;private OverScroller mScroller;private RectF mScrollerStartViewport;...private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { // Initiates the decay phase of any active edge effects. releaseEdgeEffects(); mScrollerStartViewport.set(mCurrentViewport); // Aborts any active scroll animations and invalidates. mScroller.forceFinished(true); ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this); return true; } ... @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { fling((int) -velocityX, (int) -velocityY); return true; }};private void fling(int velocityX, int velocityY) { // Initiates the decay phase of any active edge effects. releaseEdgeEffects(); // Flings use math in pixels (as opposed to math based on the viewport). Point surfaceSize = computeScrollSurfaceSize(); mScrollerStartViewport.set(mCurrentViewport); int startX = (int) (surfaceSize.x * (mScrollerStartViewport.left - AXIS_X_MIN) / ( AXIS_X_MAX - AXIS_X_MIN)); int startY = (int) (surfaceSize.y * (AXIS_Y_MAX - mScrollerStartViewport.bottom) / ( AXIS_Y_MAX - AXIS_Y_MIN)); // Before flinging, aborts the current animation. mScroller.forceFinished(true); // Begins the animation mScroller.fling( // Current scroll position startX, startY, velocityX, velocityY, /* * Minimum and maximum scroll positions. The minimum scroll * position is generally zero and the maximum scroll position * is generally the content size less the screen size. So if the * content width is 1000 pixels and the screen width is 200 * pixels, the maximum scroll offset should be 800 pixels. */ 0, surfaceSize.x - mContentRect.width(), 0, surfaceSize.y - mContentRect.height(), // The edges of the content. This comes into play when using // the EdgeEffect class to draw "glow" overlays. mContentRect.width() / 2, mContentRect.height() / 2); // Invalidates to trigger computeScroll() ViewCompat.postInvalidateOnAnimation(this);}
當onFling()方法調用postInvalidateOnAnimation()方法時,它會調用computeScroll()來更新x及y的值。
大多數View會將scroller對象的x及y的屬性值直接設定給方法scrollTo()。而下面的computeScroll()則採用了不同的方法:它調用computeScrollOffset()來擷取x及y的當前座標。當顯示的地區到達邊界時,這裡就會展示一個”glow”的效果,代碼會設定一個越過邊緣的效果,並會調用postInvalidateOnAnimation()來使View重新繪製。
// Edge effect / overscroll tracking objects.private EdgeEffectCompat mEdgeEffectTop;private EdgeEffectCompat mEdgeEffectBottom;private EdgeEffectCompat mEdgeEffectLeft;private EdgeEffectCompat mEdgeEffectRight;private boolean mEdgeEffectTopActive;private boolean mEdgeEffectBottomActive;private boolean mEdgeEffectLeftActive;private boolean mEdgeEffectRightActive;@Overridepublic void computeScroll() { super.computeScroll(); boolean needsInvalidate = false; // The scroller isn‘t finished, meaning a fling or programmatic pan // operation is currently active. if (mScroller.computeScrollOffset()) { Point surfaceSize = computeScrollSurfaceSize(); int currX = mScroller.getCurrX(); int currY = mScroller.getCurrY(); boolean canScrollX = (mCurrentViewport.left > AXIS_X_MIN || mCurrentViewport.right < AXIS_X_MAX); boolean canScrollY = (mCurrentViewport.top > AXIS_Y_MIN || mCurrentViewport.bottom < AXIS_Y_MAX); /* * If you are zoomed in and currX or currY is * outside of bounds and you‘re not already * showing overscroll, then render the overscroll * glow edge effect. */ if (canScrollX && currX < 0 && mEdgeEffectLeft.isFinished() && !mEdgeEffectLeftActive) { mEdgeEffectLeft.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectLeftActive = true; needsInvalidate = true; } else if (canScrollX && currX > (surfaceSize.x - mContentRect.width()) && mEdgeEffectRight.isFinished() && !mEdgeEffectRightActive) { mEdgeEffectRight.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectRightActive = true; needsInvalidate = true; } if (canScrollY && currY < 0 && mEdgeEffectTop.isFinished() && !mEdgeEffectTopActive) { mEdgeEffectTop.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectTopActive = true; needsInvalidate = true; } else if (canScrollY && currY > (surfaceSize.y - mContentRect.height()) && mEdgeEffectBottom.isFinished() && !mEdgeEffectBottomActive) { mEdgeEffectBottom.onAbsorb((int) OverScrollerCompat.getCurrVelocity(mScroller)); mEdgeEffectBottomActive = true; needsInvalidate = true; } ... }
下面是執行實際放大的代碼:
// Custom object that is functionally similar to ScrollerZoomer mZoomer;private PointF mZoomFocalPoint = new PointF();...// If a zoom is in progress (either programmatically or via double// touch), performs the zoom.if (mZoomer.computeZoom()) { float newWidth = (1f - mZoomer.getCurrZoom()) * mScrollerStartViewport.width(); float newHeight = (1f - mZoomer.getCurrZoom()) * mScrollerStartViewport.height(); float pointWithinViewportX = (mZoomFocalPoint.x - mScrollerStartViewport.left) / mScrollerStartViewport.width(); float pointWithinViewportY = (mZoomFocalPoint.y - mScrollerStartViewport.top) / mScrollerStartViewport.height(); mCurrentViewport.set( mZoomFocalPoint.x - newWidth * pointWithinViewportX, mZoomFocalPoint.y - newHeight * pointWithinViewportY, mZoomFocalPoint.x + newWidth * (1 - pointWithinViewportX), mZoomFocalPoint.y + newHeight * (1 - pointWithinViewportY)); constrainViewport(); needsInvalidate = true;}if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this);}
下面是computeScrollSurfaceSize()方法的內容。它計算了當前可滑動的介面的尺寸,以像素為單位。舉個例子,如果整個圖表區域是可見的,那麼它的值就等於mContentRect。如果表徵圖被放大了200%,那麼返回的值就是水平及垂直方向值的兩倍。
private Point computeScrollSurfaceSize() { return new Point( (int) (mContentRect.width() * (AXIS_X_MAX - AXIS_X_MIN) / mCurrentViewport.width()), (int) (mContentRect.height() * (AXIS_Y_MAX - AXIS_Y_MIN) / mCurrentViewport.height()));}
Android官方開發文檔Training系列課程中文版:手勢處理之滾動動畫及Scroller