android 全局頁面滑動返回聯(lián)動效果的實現(xiàn)

轉載請標明出處:http://www.itdecent.cn/p/705c2397a7f9
主要參考項目:https://github.com/ikew0ng/SwipeBackLayout

背景

首次通過向右滑動來返回的操作是在 IOS7系統(tǒng)上出現(xiàn),android系統(tǒng)特性上并不支持兩個activity間的滑動返回,但是android上有很多關于滑動的api,通過這些api也是可以實現(xiàn)視覺上的滑動返回效果。

效果圖

下層聯(lián)動滑動返回

原理的簡單描述

首先設置activity的背景是透明的,然后讓每個頁面的DecorView下添加一個自定義的ViewGroup(SwipeBackLayout),讓原先的DecorView里的子view添加到SwipeBackLayout里,通過滑動的api對SwipeBackLayout里的view進行滑動,當滑動結束后就finish當前的activity,為了實現(xiàn)聯(lián)動,在滑動的過程中拿到下層的activity的SwipeBackLayout進行滑動操作即可。

布局圖

Hierarchy View

實現(xiàn)

主要有以下四個類:
SwipeBackActivity //滑動返回基類
SwipeBackLayout //滑動返回viewGroup
SwipeBackLayoutDragHelper //修改ViewDragHelper后助手類
TranslucentHelper //代碼中修改透明或者不透明的助手類

1. 設置activity為透明

這個看起來很簡單,其實在實際開發(fā)中遇到過一個比較麻煩的頁面切換動畫的問題。在代碼中,和activity透明背景相關的地方有兩個:

  • 第一個是在activity的主題style里設置
<item name="android:windowBackground">@color/transparent</item> 
<item name="android:windowIsTranslucent">true</item>

但是問題來了,如果在某個activity的主題style中設置了android:windowIsTranslucent該屬性為true,那么該activity切換動畫變成了手機默認效果,不同手機有不同的效果,有些手機上完全不能看。于是需要自定義activity的切換動畫(windowAnimationStyle),但是又發(fā)現(xiàn)以下幾個屬性是無效的

<!-- activity 新創(chuàng)建時進來的動畫-->
<item name="android:activityOpenEnterAnimation">@anim/activity_open_enter</item>
<!-- 上層activity返回后,下層activity重新出現(xiàn)的動畫-->
<item name="android:activityOpenExitAnimation">@anim/activity_open_exit</item>
<!-- 跳到新的activity后,該activity被隱藏時的動畫-->
<item name="android:activityCloseEnterAnimation">@anim/activity_close_enter</item>
<!-- activity 銷毀時的動畫-->
<item name="android:activityCloseExitAnimation">@anim/activity_close_exit</item> 

在網(wǎng)上搜了下,發(fā)現(xiàn)下面兩個屬性還是可以用的

<item name="windowEnterAnimation">@anim/***</item>
<item name="windowExitAnimation">@anim/***</item>

但是這個在一個真正的項目中明顯是不夠的,一個是窗口進來動畫,一個是窗口退出動畫,因此還需要在代碼中動態(tài)設置,也就有了TranslucentHelper 助手類。

  • 第二個透明助手類(TranslucentHelper)里主要又有兩個方法,一個是讓activity變透明,一個是讓activity變不透明,這兩個都是通過反射來調(diào)用隱藏的系統(tǒng)api來實現(xiàn)的。
public class TranslucentHelper {

    public interface TranslucentListener {
        void onTranslucent();
    }

    private static class MyInvocationHandler implements InvocationHandler {
        private TranslucentListener listener;

        MyInvocationHandler(TranslucentListener listener) {
            this.listener = listener;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                boolean success = (boolean) args[0];
                if (success && listener != null) {
                    listener.onTranslucent();
                }
            } catch (Exception ignored) {
            }
            return null;
        }
    }

    public static boolean convertActivityFromTranslucent(Activity activity) {
        try {
            Method method = Activity.class.getDeclaredMethod("convertFromTranslucent");
            method.setAccessible(true);
            method.invoke(activity);
            return true;
        } catch (Throwable t) {
            return false;
        }
    }

    public static void convertActivityToTranslucent(Activity activity, final TranslucentListener listener) {
        try {
            Class<?>[] classes = Activity.class.getDeclaredClasses();
            Class<?> translucentConversionListenerClazz = null;
            for (Class clazz : classes) {
                if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
                    translucentConversionListenerClazz = clazz;
                }
            }

            MyInvocationHandler myInvocationHandler = new MyInvocationHandler(listener);
            Object obj = Proxy.newProxyInstance(Activity.class.getClassLoader(),
                    new Class[] { translucentConversionListenerClazz }, myInvocationHandler);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions");
                getActivityOptions.setAccessible(true);
                Object options = getActivityOptions.invoke(activity);

                Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
                        translucentConversionListenerClazz, ActivityOptions.class);
                method.setAccessible(true);
                method.invoke(activity, obj, options);
            } else {
                Method method =
                        Activity.class.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz);
                method.setAccessible(true);
                method.invoke(activity, obj);
            }
        } catch (Throwable t) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (listener != null) {
                        listener.onTranslucent();
                    }
                }
            }, 100);
        }
    }
}

讓activity變不透明的方法比較簡單就不多說了;讓activity變透明的方法參數(shù)里出入了一個listener ,這個后面再講,主要看調(diào)用invoke方法時,判斷了版本是否是大于等于5.0,如果是,需要再傳入一個ActivityOptions參數(shù)。

2. 讓BaseActivity繼承SwipeBackActivity

先直接看代碼,比較少

public class SwipeBackActivity extends FragmentActivity {
    /**
     * 滑動返回ViewGroup
     */
    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSwipeBackLayout = new SwipeBackLayout(this);
        getWindow().setBackgroundDrawableResource(R.color.transparent);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mSwipeBackLayout.attachToActivity(this);
        mSwipeBackLayout.setOnSwipeBackListener(new SwipeBackLayout.onSwipeBackListener() {
            @Override
            public void onStart() {
                onSwipeBackStart();
            }

            @Override
            public void onEnd() {
                onSwipeBackEnd();
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getSwipeBackLayout().recovery();
        }
    }

    /**
     * 滑動返回開始時的回調(diào)
     */
    protected void onSwipeBackStart() {

    }

    /**
     * 滑動返回結束時的回調(diào)
     */
    protected void onSwipeBackEnd() {

    }

    @Override
    public View findViewById(int id) {
        View v = super.findViewById(id);
        if (v == null && mSwipeBackLayout != null) {
            return mSwipeBackLayout.findViewById(id);
        }
        return v;
    }

    /**
     * 設置是否可以邊緣滑動返回,需要在onCreate方法調(diào)用
     */
    public void setSwipeBackEnable(boolean enable) {
        mSwipeBackLayout.setSwipeBackEnable(enable);
    }

    public SwipeBackLayout getSwipeBackLayout() {
        return mSwipeBackLayout;
    }
}

SwipeBackActivity中包含了一個SwipeBackLayout ,在onCreate方法中,new了一個SwipeBackLayout 、設置了window的背景色為透明色、主題設置為不透明。不要被這個透明搞暈了,window的背景色相當于在style中設置android:windowBackground為透明,這個也是activity透明的必要條件,由于我所開發(fā)的這個項目已經(jīng)迭代了很多個版本,activity很多,而這些activity中android:windowBackground設置的顏色大部分是白色,少部分是灰色和透明的,所以需要在代碼中設置統(tǒng)一設置一遍透明的,以達到最少修改代碼的目的,如果是一個新的項目,可以直接在style中寫死windowBackground為透明,這樣就不要再代碼中設置了。那么問題是在代碼中設置了window是透明的,原來如果是灰色的視覺效果被影響到了怎么辦?解決辦法是獲取原來的背景色賦值給原來DecorView的子view(也就是現(xiàn)在SwipeBackLayout的子view)就可以了。背景色賦值就是在onPostCreate方法的mSwipeBackLayout.attachToActivity(this);里做的。onPostCreate的執(zhí)行時機是在onStart和onResume之間的。attachToActivity就是將SwipeBackLayout插入到DecorView和其子view之間,可以先看下代碼:

/**
 * 將View添加到Activity
 */
public void attachToActivity(Activity activity) {
    mTopActivity = activity;
    TypedArray a = activity.getTheme().obtainStyledAttributes(new int[] {
            android.R.attr.windowBackground
    });
    int background = a.getResourceId(0, 0);
    a.recycle();

    ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
    ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
    decorChild.setBackgroundResource(background);
    decor.removeView(decorChild);
    addView(decorChild);
    setContentView(decorChild);
    decor.addView(this);

    Activity backActivity = ActivityUtils.getSecondTopActivity();
    if (backActivity != null && backActivity instanceof SwipeBackActivity) {
        mBackActivityWeakRf = new WeakReference<>(backActivity);
    }
}

代碼整體上都還是比較簡單的,應該都能看懂。前面是獲取window背景色,插入過程到decor.addView(this);為止,下面拿到backActivity 的引用是為了做到下層activity聯(lián)動時用到的。

繼續(xù)來看SwipeBackActivity,onPostCreate還設置了開始滑動和滑動結束的回調(diào),在某些場合下還是需要的,比如一些PopupWindow在滑動返回時不會被消除,這個時候可以在onSwipeBackStart()調(diào)用其dismiss()方法。在onWindowFocusChanged中如果是hasFocus == true,就recovery()這個SwipeBackLayout,這個也是因為下層activity有聯(lián)動效果而移動了SwipeBackLayout,所以需要recovery()下,防止異常情況。最后再提下setSwipeBackEnable(…),某些不可以滑動返回的頁面比如MainActivity需要在其onCreate方法中調(diào)用下設置為false就可以了。

3. SwipeBackLayout和SwipeBackLayoutDragHelper


    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        //繪制陰影
        if (mContentPercent > 0
                && child == mContentView
                && mViewDragHelper.getViewDragState() != SwipeBackLayoutDragHelper.STATE_IDLE) {
            child.getHitRect(mContentViewRect);
            mShadowLeft.setBounds(mContentViewRect.left - mShadowLeft.getIntrinsicWidth(), mContentViewRect.top,
                    mContentViewRect.left, mContentViewRect.bottom);
            //mShadowLeft.setAlpha((int) (mContentPercent * FULL_ALPHA));
            mShadowLeft.draw(canvas);
        }
        return super.drawChild(canvas, child, drawingTime);
    }

    @Override
    public void computeScroll() {
        mContentPercent = 1 - mScrollPercent;
        if (mViewDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
    }

    /**
     * 設置是否可以滑動返回
     */
    public void setSwipeBackEnable(boolean enable) {
        mIsSwipeBackEnable = enable;
    }

    public boolean isActivityTranslucent() {
        return mIsActivityTranslucent;
    }

    /**
     * 啟動進入動畫
     */
    private void startEnterAnim() {
        if (mContentView != null) {
            ObjectAnimator anim = ObjectAnimator
                    .ofFloat(mContentView, "TranslationX", mContentView.getTranslationX(), 0f);
            anim.setDuration((long) (125 * mContentPercent));
            mEnterAnim = anim;
            mEnterAnim.start();
        }
    }

    protected View getContentView() {
        return mContentView;
    }

    private void setContentView(ViewGroup decorChild) {
        mContentView = decorChild;
    }

    private class ViewDragCallback extends SwipeBackLayoutDragHelper.Callback {
        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            if (mIsSwipeBackEnable && mViewDragHelper.isEdgeTouched(SwipeBackLayoutDragHelper.EDGE_LEFT, pointerId)) {
                TranslucentHelper.convertActivityToTranslucent(mTopActivity,
                        new TranslucentHelper.TranslucentListener() {
                            @Override
                            public void onTranslucent() {
                                if (mListener != null) {
                                    mListener.onStart();
                                }
                                mIsActivityTranslucent = true;
                            }
                        });
                return true;
            }
            return false;
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            return mIsSwipeBackEnable ? SwipeBackLayoutDragHelper.EDGE_LEFT : 0;
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            super.onViewPositionChanged(changedView, left, top, dx, dy);
            if (changedView == mContentView) {
                mScrollPercent = Math.abs((float) left / mContentView.getWidth());
                mContentLeft = left;
                //未執(zhí)行動畫就平移
                if (!mIsEnterAnimRunning) {
                    moveBackActivity();
                }
                invalidate();
                if (mScrollPercent >= 1 && !mTopActivity.isFinishing()) {
                    if (mBackActivityWeakRf != null && ActivityUtils.activityIsAlive(mBackActivityWeakRf.get())) {
                        ((SwipeBackActivity) mBackActivityWeakRf.get()).getSwipeBackLayout().invalidate();
                    }
                    mTopActivity.finish();
                    mTopActivity.overridePendingTransition(0, 0);
                }
            }
        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            if (xvel > DEFAULT_VELOCITY_THRESHOLD || mScrollPercent > DEFAULT_SCROLL_THRESHOLD){
                if (mIsActivityTranslucent) {
                    mViewDragHelper.settleCapturedViewAt(releasedChild.getWidth() + mShadowLeft.getIntrinsicWidth(), 0);
                    if (mContentPercent < 0.85f) {
                        startAnimOfBackActivity();
                    }
                }
            } else {
                mViewDragHelper.settleCapturedViewAt(0, 0);
            }
            if (mListener != null) {
                mListener.onEnd();
            }
            invalidate();
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            return Math.min(child.getWidth(), Math.max(left, 0));
        }

        @Override
        public void onViewDragStateChanged(int state) {
            super.onViewDragStateChanged(state);

            if (state == SwipeBackLayoutDragHelper.STATE_IDLE && mScrollPercent < 1f) {
                TranslucentHelper.convertActivityFromTranslucent(mTopActivity);
                mIsActivityTranslucent = false;
            }
        }

        @Override
        public boolean isTranslucent() {
            return SwipeBackLayout.this.isActivityTranslucent();
        }
    }

    /**
     * 背景Activity開始進入動畫
     */
    private void startAnimOfBackActivity() {
        if (mBackActivityWeakRf != null && ActivityUtils.activityIsAlive(mBackActivityWeakRf.get())) {
            mIsEnterAnimRunning = true;
            SwipeBackLayout swipeBackLayout = ((SwipeBackActivity) mBackActivityWeakRf.get()).getSwipeBackLayout();
            swipeBackLayout.startEnterAnim();
        }
    }

    /**
     * 移動背景Activity
     */
    private void moveBackActivity() {
        if (mBackActivityWeakRf != null && ActivityUtils.activityIsAlive(mBackActivityWeakRf.get())) {
            View view = ((SwipeBackActivity) mBackActivityWeakRf.get()).getSwipeBackLayout().getContentView();
            if (view != null) {
                int width = view.getWidth();
                view.setTranslationX(-width * 0.3f * Math.max(0f, mContentPercent - 0.15f));
            }
        }
    }

    /**
     * 回復界面的平移到初始位置
     */
    public void recovery() {
        if (mEnterAnim != null && mEnterAnim.isRunning()) {
            mEnterAnim.end();
        } else {
            mContentView.setTranslationX(0);
        }
    }

}

drawChild是來繪制了左側陰影的,獲取到原 子view 所在屏幕的矩形,之后確定陰影所在的矩形,然后就直接繪制了。

child.getHitRect(mContentViewRect);
mShadowLeft.setBounds(mContentViewRect.left - mShadowLeft.getIntrinsicWidth(), mContentViewRect.top,
mContentViewRect.left, mContentViewRect.bottom);
mShadowLeft.draw(canvas);

代碼中滑動是用了ViewDragHelper,如果不熟悉這個類需要先自行百度。只是這個官方封裝類有幾個地方不能滿足這個滑動返回的需求,于是就有了SwipeBackLayoutDragHelper,SwipeBackLayoutDragHelper主要是copy了ViewDragHelper源碼后再添加了一些代碼。

首先原生ViewDragHelper里面沒有setMaxVelocity方法,如果滑動過快,會導致下層聯(lián)動滑動跟不上,上層滑動結束后下層還沒移動好,這導致的結果就是下下層可以被看到,下下層也許就是手機桌面,影響了體驗,所以需要設置了最大速度。

我們知道ViewDragHelper需要通過shouldInterceptTouchEvent(event)和processTouchEvent(event)獲取該view的onInterceptTouchEvent和onTouchEvent事件,之后設置一個回調(diào)ViewDragCallback里面寫幾個方法就基本上可以實現(xiàn)用手指拖拽了,回調(diào)中有許多的方法,其中isTranslucent()是自己添加進去的,接下來就講講重寫回調(diào)里的方法都做了什么。

Callback
@Override
public boolean tryCaptureView(View child, int pointerId) {
    if (mIsSwipeBackEnable && mViewDragHelper.isEdgeTouched(SwipeBackLayoutDragHelper.EDGE_LEFT, pointerId)) {
        TranslucentHelper.convertActivityToTranslucent(mTopActivity,
                new TranslucentHelper.TranslucentListener() {
                    @Override
                    public void onTranslucent() {
                        if (mListener != null) {
                            mListener.onStart();
                        }
                        mIsActivityTranslucent = true;
                    }
                });
        return true;
    }
    return false;
}

** tryCaptureView**方法當觸摸到SwipeBackLayout里的子View時觸發(fā)的,當返回true,表示捕捉成功,否則失敗。判斷條件是如果支持滑動返回并且是左側邊距被觸摸時才可以,我們知道這個時候的的背景色是不透明的,如果直接開始滑動則是黑色的,所以需要在這里背景色改成透明的,如果直接調(diào)用 TranslucentHelper.convertActivityToTranslucent(mTopActivity)后直接返回true,會出現(xiàn)一個異常情況,就是滑動過快時會導致背景還來不及變成黑色就滑動出來了,之后才變成透明的,從而導致了會從黑色到透明的一個閃爍現(xiàn)象,解決的辦法是在代碼中用了一個回調(diào)和標記,當變成透明后設置了mIsActivityTranslucent = true;通過mIsActivityTranslucent 這個變量來判斷是否進行移動的操作。由于修改activity變透明的方法是通過反射的,不能簡單的設置一個接口后進行回調(diào),而是通過動態(tài)代理的方式來實現(xiàn)的(InvocationHandler),在convertToTranslucent方法的第一個參數(shù)剛好是一個判斷activity是否已經(jīng)變成透明的回調(diào),看下面代碼中 if 語句里的注釋和回調(diào),如果窗口已經(jīng)變成透明的話,就傳了一個drawComplete (true)。

@SystemApi
public boolean convertToTranslucent(TranslucentConversionListener callback,
        ActivityOptions options) {
    boolean drawComplete;
    try {
        mTranslucentCallback = callback;
        mChangeCanvasToTranslucent =
                ActivityManagerNative.getDefault().convertToTranslucent(mToken, options);
        WindowManagerGlobal.getInstance().changeCanvasOpacity(mToken, false);
        drawComplete = true;
    } catch (RemoteException e) {
        // Make callback return as though it timed out.
        mChangeCanvasToTranslucent = false;
        drawComplete = false;
    }
    if (!mChangeCanvasToTranslucent && mTranslucentCallback != null) {
        // Window is already translucent.
        mTranslucentCallback.onTranslucentConversionComplete(drawComplete);
    }
    return mChangeCanvasToTranslucent;
}

在TranslucentHelper的convertActivityToTranslucent(…)方法中

MyInvocationHandler myInvocationHandler =
        new MyInvocationHandler(new WeakReference<>(listener));
Object obj = Proxy.newProxyInstance(Activity.class.getClassLoader(),
        new Class[] { translucentConversionListenerClazz }, myInvocationHandler);

通過動態(tài)代理,將translucentConversionListenerClazz 執(zhí)行其方法onTranslucentConversionComplete的替換成myInvocationHandler中執(zhí)行invoke方法。

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        boolean success = (boolean) args[0];
        if (success && listener.get() != null) {
            listener.get().onTranslucent();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

其中賦值給success的args[0]正是 drawComplete
mTranslucentCallback.onTranslucentConversionComplete(drawComplete);

isTranslucent是上面提到,在SwipeBackLayoutDragHelper中的Callback回調(diào)里,自己添加了一個方法,主要是返回activity是否是透明的

public boolean isTranslucent() {
    return true;
}

默認為true,在SwipeBackLayout重寫后將mIsActivityTranslucent返回SwipeBackLayoutDragHelper

@Override
public boolean isTranslucent() {
    return SwipeBackLayout.this.isActivityTranslucent();
}

仔細看SwipeBackLayoutDragHelper方法的話,會發(fā)現(xiàn)最后通過dragTo方法對view進行移動,因此在進行水平移動前判斷下是否是透明的,只有透明了才能移動

private void dragTo(int left, int top, int dx, int dy) {
    int clampedX = left;
    int clampedY = top;
    final int oldLeft = mCapturedView.getLeft();
    final int oldTop = mCapturedView.getTop();
    if (dx != 0) {
        clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx);
        if (mCallback.isTranslucent()) {
            ViewCompat.offsetLeftAndRight(mCapturedView, clampedX - oldLeft);
        }
    }
    if (dy != 0) {
        clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy);
        ViewCompat.offsetTopAndBottom(mCapturedView, clampedY - oldTop);
    }

    if (dx != 0 || dy != 0) {
        final int clampedDx = clampedX - oldLeft;
        final int clampedDy = clampedY - oldTop;
        if (mCallback.isTranslucent()) {
            mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY,
                    clampedDx, clampedDy);
        }
    }
}

onViewPositionChanged view移動過程中會持續(xù)調(diào)用,這里面的邏輯主要有這幾個:
實時計算滑動了多少距離,用于繪制左側陰影等
使下面的activity進行移動moveBackActivity();
當view完全移出屏幕后,銷毀當前的activity

@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
    super.onViewPositionChanged(changedView, left, top, dx, dy);
    if (changedView == mContentView) {
        mScrollPercent = Math.abs((float) left / mContentView.getWidth());
        mContentLeft = left;
        //未執(zhí)行動畫就平移
        if (!mIsEnterAnimRunning) {
            moveBackActivity();
        }
        invalidate();
        if (mScrollPercent >= 1 && !mTopActivity.isFinishing()) {
            if (mBackActivityWeakRf != null && ActivityUtils.activityIsAlive(mBackActivityWeakRf.get())) {
                ((SwipeBackActivity) mBackActivityWeakRf.get()).getSwipeBackLayout().invalidate();
            }
            mTopActivity.finish();
            mTopActivity.overridePendingTransition(0, 0);
        }
    }
}
/**
     * 移動背景Activity
     */
    private void moveBackActivity() {
        if (mBackActivityWeakRf != null && ActivityUtils.activityIsAlive(mBackActivityWeakRf.get())) {
            View view = ((SwipeBackActivity) mBackActivityWeakRf.get()).getSwipeBackLayout().getContentView();
            if (view != null) {
                int width = view.getWidth();
                view.setTranslationX(-width * 0.3f * Math.max(0f, mContentPercent - 0.15f));
            }
        }
    }

onViewReleased是手指釋放后觸發(fā)的一個方法
如果滑動速度大于最大速度或者滑動的距離大于設定的閾值距離,則直接移到屏幕外,同時觸發(fā)下層activity的復位動畫mViewDragHelper.settleCapturedViewAt(releasedChild.getWidth() + mShadowLeft.getIntrinsicWidth(), 0);
否則移會到原來位置 mViewDragHelper.settleCapturedViewAt(0, 0);

@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
    if (xvel > DEFAULT_VELOCITY_THRESHOLD || mScrollPercent > DEFAULT_SCROLL_THRESHOLD){
        if (mIsActivityTranslucent) {
            mViewDragHelper.settleCapturedViewAt(releasedChild.getWidth() + mShadowLeft.getIntrinsicWidth(), 0);
            if (mContentPercent < 0.85f) {
                startAnimOfBackActivity();
            }
        }
    } else {
        mViewDragHelper.settleCapturedViewAt(0, 0);
    }
    if (mListener != null) {
        mListener.onEnd();
    }
    invalidate();
}
/**
 * 背景Activity開始進入動畫
 */
private void startAnimOfBackActivity() {
    if (mBackActivityWeakRf != null && ActivityUtils.activityIsAlive(mBackActivityWeakRf.get())) {
        mIsEnterAnimRunning = true;
        SwipeBackLayout swipeBackLayout = ((SwipeBackActivity) mBackActivityWeakRf.get()).getSwipeBackLayout();
        swipeBackLayout.startEnterAnim();
    }
}
/**
 * 啟動進入動畫
 */
private void startEnterAnim() {
    if (mContentView != null) {
        ObjectAnimator anim = ObjectAnimator
                .ofFloat(mContentView, "TranslationX", mContentView.getTranslationX(), 0f);
        anim.setDuration((long) (125 * mContentPercent));
        mEnterAnim = anim;
        mEnterAnim.start();
    }
}

onViewDragStateChanged當滑動的狀態(tài)發(fā)生改變時的回調(diào)
主要是停止滑動后,將背景改成不透明,這樣跳到別的頁面是動畫就是正常的。

@Override
public void onViewDragStateChanged(int state) {
    super.onViewDragStateChanged(state);

    if (state == SwipeBackLayoutDragHelper.STATE_IDLE && mScrollPercent < 1f) {
        TranslucentHelper.convertActivityFromTranslucent(mTopActivity);
        mIsActivityTranslucent = false;
    }
}

clampViewPositionHorizontal 返回水平移動距離,下面這樣寫可以防止滑出父 view

@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
    return Math.min(child.getWidth(), Math.max(left, 0));
}

getViewHorizontalDragRange對于clickable=true的子view,需要返回大于0的數(shù)字才能正常捕獲。

@Override
public int getViewHorizontalDragRange(View child) {
    return mIsSwipeBackEnable ? SwipeBackLayoutDragHelper.EDGE_LEFT : 0;
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容