如何利用RecyclerView打造炫酷滑動卡片

DorMcMurray 8年前發布 | 14K 次閱讀 Java開發 RecyclerView

前段時間一直在B站追《黑鏡》第三季,相比前幾季,這季很良心的拍了六集,:smile:著實過了一把癮。由于看的是字幕組貢獻的版本,每集開頭都插了一個app的廣告,叫“人人美劇”,一向喜歡看美劇的我便掃了一下二維碼,安裝了試一試。我打開app,匆匆滑動了一下首頁的美劇列表,然后便隨手切換到了訂閱頁面,然后,我就被訂閱頁面的動畫效果吸引住了。

沒錯,就是上面這玩意兒,是不是很炫酷,本著發揚一名碼農的職業精神,我心里便癢癢的想實現這種效果,當然因為長期的fork compile,第一時間我還是上網搜了搜,有木有哪位好心人已經開源了類似的控件。借助強大的Google,我馬上搜到了一個項目 SwipeCards ,是仿照探探的老父親Tinder的app動畫效果打造的,果然程序員都一個操行,看到好看的就想動手實現,不過人家的成績讓我可望而不可及~

他實現的效果是這樣的:

嗯,還不錯,為了進行思想上的碰撞,我就download了一下他的源碼,稍稍read了一下~_~

作為一個有思想,有抱負的程序員,怎么能滿足于compile別人的庫呢?必須得自己動手,豐衣足食啊!

開工

###思考

一般這種View都是自定義的,然后重寫onLayout,但是有木有更簡單的方法呢?由于項目里一直使用RecyclerView,那么能不能用RecyclerView來實現這種效果呢?能,當然能啊!得力于RecyclerView優雅的擴展性,我們完全可以自定義一個LayoutManager來實現嘛。

布局實現

RecyclerView可以通過自定義LayoutManager來實現各種布局,官方自己提供了LinearLayoutManager、GridLayoutManager,相比于ListView,可謂是方便了不少。同樣,我們也可以通過自定義LayoutManager,實現這種View一層層疊加的效果。

自定義LayoutManager,最重要的是要重寫onLayoutChildren()

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    detachAndScrapAttachedViews(recycler);
    for (int i = 0; i < getItemCount(); i++) {
        View child = recycler.getViewForPosition(i);
        measureChildWithMargins(child, 0, 0);
        addView(child);
        int width = getDecoratedMeasuredWidth(child);
        int height = getDecoratedMeasuredHeight(child);
        layoutDecorated(child, 0, 0, width, height);
        if (i < getItemCount() - 1) {
            child.setScaleX(0.8f);
            child.setScaleY(0.8f);
        }
    }
}

這種布局實現起來其實相當簡單,因為每個child的left和top都一樣,直接設置為0就可以了,這樣child就依次疊加在一起了,至于最后兩句,主要是為了使頂部Child之下的childs有一種縮放的效果。

動畫實現

下面到了最重要的地方了,主要分為以下幾個部分。

(1)手勢追蹤

當手指按下時,我們需要取到RecyclerView的頂部Child,并讓其跟隨手指滑動。

public boolean onTouchEvent(MotionEvent e) {
    if (getChildCount() == 0) {
        return super.onTouchEvent(e);
    }
    View topView = getChildAt(getChildCount() - 1);
    float touchX = e.getX();
    float touchY = e.getY();
    switch (e.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mTopViewX = topView.getX();
            mTopViewY = topView.getY();
            mTouchDownX = touchX;
            mTouchDownY = touchY;
            break;
        case MotionEvent.ACTION_MOVE:
            float dx = touchX - mTouchDownX;
            float dy = touchY - mTouchDownY;
            topView.setX(mTopViewX + dx);
            topView.setY(mTopViewY + dy);
            updateNextItem(Math.abs(topView.getX() - mTopViewX) * 0.2 / mBorder + 0.8);
            break;
        case MotionEvent.ACTION_UP:
            mTouchDownX = 0;
            mTouchDownY = 0;
            touchUp(topView);
            break;
    }
    return super.onTouchEvent(e);
}

手指按下的時候,記錄topChildView的位置,移動的時候,根據偏移量,動態調整topChildView的位置,就實現了基本效果。但是這樣還不夠,記得我們在實現布局時,對其他子View進行了縮放嗎?那時候的縮放是為現在做準備的。當手指在屏幕上滑動時,我們同樣會調用updateNextItem(),對topChildView下面的子view進行縮放。

private void updateNextItem(double factor) {
    if (getChildCount() < 2) {
        return;
    }
    if (factor > 1) {
        factor = 1;
    }
    View nextView = getChildAt(getChildCount() - 2);
    nextView.setScaleX((float) factor);
    nextView.setScaleY((float) factor);
}

這里的factor計算很簡單,只要當topChildView滑動到設置的邊界時,nextView剛好縮放到原本大小,即factor=1,就可以了。因為nextView一開始縮放為0.8,所以可計算出:

factor=Math.abs(topView.getX() - mTopViewX) * 0.2 / mBorder + 0.8

(2)抬起手指

手指抬起后,我們要進行狀態判斷

1.滑動未超過邊界

此時我們需要對topChildView進行歸位。

2.超過邊界

此時我們需要根據滑動方向,使topChildView飛離屏幕。

對于這兩種情況,我們都是通過計算view的終點坐標,然后利用動畫實現的。對于第一種,很簡單,targetX和targetY直接就是topChildView的原始坐標。但是對于第二種,需要根據topChildView的原始坐標和目前坐標,計算出線性表達式,然后再根據targetX來計算targetY,至于targetX,往右飛targetX就可以賦為getScreenWidth,而往左就直接為0-view.width,只要終點在屏幕外就可以。具體代碼如下。

private void touchUp(final View view) {
    float targetX = 0;
    float targetY = 0;
    boolean del = false;
    if (Math.abs(view.getX() - mTopViewX) < mBorder) {
        targetX = mTopViewX;
        targetY = mTopViewY;
    } else if (view.getX() - mTopViewX > mBorder) {
        del = true;
        targetX = getScreenWidth()*2;
        mRemovedListener.onRightRemoved();
    } else {
        del = true;
        targetX = -view.getWidth()-getScreenWidth();
        mRemovedListener.onLeftRemoved();
    }
    View animView = view;
    TimeInterpolator interpolator = null;
    if (del) {
        animView = getMirrorView(view);
        float offsetX = getX() - mDecorView.getX();
        float offsetY = getY() - mDecorView.getY();
        targetY = caculateExitY(mTopViewX + offsetX, mTopViewY + offsetY, animView.getX(), animView.getY(), targetX);
        interpolator = new LinearInterpolator();
    } else {
        interpolator = new OvershootInterpolator();
    }
    final boolean finalDel = del;
    animView.animate()
            .setDuration(500)
            .x(targetX)
            .y(targetY)
            .setInterpolator(interpolator)
            .setUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    if (!finalDel) {
                        updateNextItem(Math.abs(view.getX() - mTopViewX) * 0.2 / mBorder + 0.8);
                    }
                }
            });

}

對于第二種情況,如果直接啟動動畫,并在動畫結束時通知adapter刪除item,在連續操作時,會導致數據錯亂。但是如果在動畫啟動時直接移除item,又會失去動畫效果。所以我在這里采用了另一種辦法,在動畫開始前創建一個與topChildView一模一樣的鏡像View,添加到DecorView上,并隱藏刪除掉topChildView,然后利用鏡像View來展示動畫。添加鏡像View的代碼如下:

private ImageView getMirrorView(View view) {
    view.destroyDrawingCache();
    view.setDrawingCacheEnabled(true);
    final ImageView mirrorView = new ImageView(getContext());
    Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
    mirrorView.setImageBitmap(bitmap);
    view.setDrawingCacheEnabled(false);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(bitmap.getWidth(), bitmap.getHeight());
    int[] locations = new int[2];
    view.getLocationOnScreen(locations);

    mirrorView.setAlpha(view.getAlpha());
    view.setVisibility(GONE);
    ((SwipeCardAdapter) getAdapter()).delTopItem();
    mirrorView.setX(locations[0] - mDecorViewLocation[0]);
    mirrorView.setY(locations[1] - mDecorViewLocation[1]);
    mDecorView.addView(mirrorView, params);
    return mirrorView;
}

因為鏡像View是添加在DecorView上的,topChildView父容器是RecyclerVIew,而View的x、y是相對于父容器而言的,所以鏡像View的targetX和targetY需要加上一定偏移量。

好了到這里,一切就準備就緒了,下面讓我們看看動畫效果如何。

 

來自:https://halfstackdeveloper.github.io/2016/11/09/如何利用RecyclerView打造炫酷滑動卡片/

 

 本文由用戶 DorMcMurray 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!