Android官方開發文件Training系列課程中文版:手勢處理之滾動動畫及Scroller
在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);
}
大多數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;
@Override
public 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 Scroller
Zoomer 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()));
}