Android 滾動手勢動畫

2018-08-02 18:21 更新

編寫:Andrwyw - 原文:http://developer.android.com/training/gestures/scroll.html

在Android中,通常使用ScrollView類來實現(xiàn)滾動(scroll)。任何可能超過父類邊界的布局,都應(yīng)該嵌套在ScrollView中,來提供一個由系統(tǒng)框架管理的可滾動的view。僅在某些特殊情形下,我們才要實現(xiàn)一個自定義scroller。本節(jié)課程就描述了這樣一個情形:使用 scrollers 顯示滾動效果,以響應(yīng)觸摸手勢。

為了收集數(shù)據(jù)來產(chǎn)生滾動動畫,以響應(yīng)一個觸摸事件,我們可以使用scrollers(Scroller或者OverScroller)。這兩個類很相似,但OverScroller有一些函數(shù),能在平移或快速滑動手勢后,向用戶指出已經(jīng)達(dá)到內(nèi)容的邊緣。InteractiveChart 例子使用了EdgeEffect類(實際上是EdgeEffectCompat類),在用戶到達(dá)內(nèi)容的邊緣時顯示“發(fā)光”效果。

Note: 比起Scroller類,我們更推薦使用OverScroller類來產(chǎn)生滾動動畫。OverScroller類為老設(shè)備提供了很好的向后兼容性。 另外需要注意的是,僅當(dāng)我們要自己實現(xiàn)滾動時,才需要使用scrollers。如果我們把布局嵌套在ScrollViewHorizontalScrollView中,它們會幫我們把這些做好。

通過使用平臺標(biāo)準(zhǔn)的滾動物理因素(摩擦、速度等),scroller被用來隨著時間的推移產(chǎn)生滾動動畫。實際上,scroller本身不會繪制任何東西。Scrollers只是隨著時間的推移,追蹤滾動的偏移量,但它們不會自動地把這些位置應(yīng)用到view上。我們應(yīng)該按一定頻率,獲取并應(yīng)用這些新的坐標(biāo)值,來讓滾動動畫更加順滑。

理解滾動術(shù)語

在Android中,“Scrolling”這個詞根據(jù)不同情景有著不同的含義。

滾動(Scrolling)是指移動視窗(viewport)(指你正在看的內(nèi)容所在的‘窗口’)的一般過程。當(dāng)在x軸和y軸方向同時滾動時,就叫做平移panning)。示例程序提供的 InteractiveChart 類,展示了兩種不同類型的滾動,拖拽與快速滑動。

  • 拖拽(dragging)是滾動的一種類型,當(dāng)用戶在觸摸屏上拖動手指時發(fā)生。簡單的拖拽一般可以通過重寫 GestureDetector.OnGestureListener  onScroll() 來實現(xiàn)。關(guān)于拖拽的更多討論,可以查看拖拽與縮放章節(jié)。
  • 快速滑動(fling)這種類型的滾動,在用戶快速拖拽后,抬起手指時發(fā)生。當(dāng)用戶抬起手指后,我們通常想繼續(xù)保持滾動(移動視窗),但會一直減速直到視窗停止移動。通過重寫GestureDetector.OnGestureListeneronFling()函數(shù),使用scroller對象,可實現(xiàn)快速滑動。這種用法也就是本節(jié)課程的主題。

scroller對象通常會與快速滑動手勢結(jié)合起來使用。但在任何我們想讓UI展示滾動動畫,以響應(yīng)觸摸事件的場景,都可以用scroller對象來實現(xiàn)。比如,我們可以重寫onTouchEvent()函數(shù),直接處理觸摸事件,并且產(chǎn)生一個滾動效果或“頁面對齊”動畫(snapping to page),來響應(yīng)這些觸摸事件。

實現(xiàn)基于觸摸的滾動

本節(jié)講述如何使用scroller。下面的代碼段來自 InteractiveChart 示例。它使用GestureDetector,并且重寫了GestureDetector.SimpleOnGestureListener onFling() 函數(shù)。它使用OverScroller追蹤快速滑動(fling)手勢??焖倩瑒邮謩莺?,如果用戶到達(dá)內(nèi)容邊緣,應(yīng)用會顯示一種發(fā)光效果。

Note: InteractiveChart示例程序展示了一個可縮放、平移、滑動的表格。在接下來的代碼段中,mContentRect表示view中的一塊矩形坐標(biāo)區(qū)域,該區(qū)域?qū)⒈挥脕砝L制表格。在任意給定的時間點,表格中某一部分會被繪制在這個區(qū)域內(nèi)。mCurrentViewport表示當(dāng)前在屏幕上可見的那一部分表格。因為像素偏移量通常當(dāng)作整型處理,所以mContentRectRect類型的。因為圖表的區(qū)域范圍是數(shù)值型/浮點型值,所以mCurrentViewportRectF類型。

代碼段的第一部分展示了onFling()函數(shù)的實現(xiàn):

// 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);
}

當(dāng)onFling()函數(shù)調(diào)用postInvalidateOnAnimation()時,它會觸發(fā)computeScroll()來更新x、y的值。通常一個子view用scroller對象來產(chǎn)生滾動動畫時會這樣做,就像本例一樣。

大多數(shù)views直接通過scrollTo()函數(shù)傳遞scroller對象的x、y坐標(biāo)值。接下來的computeScroll()函數(shù)的實現(xiàn)中采用了一種不同的方式。它調(diào)用computeScrollOffset()函數(shù)來獲得當(dāng)前位置的x、y值。當(dāng)滿足邊緣顯示發(fā)光效果的條件時(圖表已被放大顯示,x或y值超過邊界,并且app當(dāng)前沒有顯示overscroll),這段代碼會設(shè)置overscroll發(fā)光效果,并調(diào)用postInvalidateOnAnimation()函數(shù)來讓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);
}

這是上面代碼段中調(diào)用過的computeScrollSurfaceSize()函數(shù)。它會以像素為單位計算當(dāng)前可滾動的尺寸。舉例來說,如果整個圖表區(qū)域都是可見的,它的值就簡單地等于mContentRect的大小。如果圖表在兩個方向上都放大到200%,此函數(shù)返回的尺寸在水平、垂直方向上都會大兩倍。

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()));
}

關(guān)于scroller用法的另一個示例,可查看ViewPager類的源代碼。它用滾動來響應(yīng)快速滑動(fling),并且使用滾動來實現(xiàn)“頁面對齊”(snapping to page)動畫。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號