1. 程式人生 > 其它 >Activity側滑返回的實現原理

Activity側滑返回的實現原理

簡介

使用側滑Activity返回很常見,例如微信就用到了。那麼它是怎麼實現的呢。本文帶你剖析一下實現原理。我在github上找了一個star有2.6k的開源,我們分析他是怎麼實現的

//star 2.6k
'com.r0adkll:slidableactivity:2.0.5'

Slidr使用示例

它的使用很簡單,首先要設定透明的視窗背景

    <style name="AppTheme"  parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="android:textAllCaps">false</item>
        <item name="android:windowActionBar">false</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
    </style>

然後

//setContent(View view)後
Slidr.attach(this);

下面可以從三個步驟看其原理

步驟一 重新包裹介面

Slidr.class

    public static SlidrInterface attach(final Activity activity, final int statusBarColor1, final int statusBarColor2){
        //0  建立滑動巢狀介面SliderPanel
		final SliderPanel panel = initSliderPanel(activity, null);

        //7 Set the panel slide listener for when it becomes closed or opened
        // 監聽回撥
        panel.setOnPanelSlideListener(new SliderPanel.OnPanelSlideListener() {
			...
            //open close等
        });

		// Return the lock interface
		return initInterface(panel);
    }

	private static SliderPanel initSliderPanel(final Activity activity, final SlidrConfig config) {
		//3 獲取decorview
		ViewGroup decorView = (ViewGroup)activity.getWindow().getDecorView();
        
        //4 獲取我們佈局的內容並刪除
		View oldScreen = decorView.getChildAt(0);
		decorView.removeViewAt(0);

		//5 Setup the slider panel and attach it to the decor
        // 建立滑動巢狀檢視SliderPanel並且新增到DecorView中
		SliderPanel panel = new SliderPanel(activity, oldScreen, config);
		panel.setId(R.id.slidable_panel);
		oldScreen.setId(R.id.slidable_content);
        
        //6 把我們的介面佈局新增到SliderPanel,並且把SliderPanel新增到decorView中
		panel.addView(oldScreen);
		decorView.addView(panel, 0);
		return panel;
	}

步驟二 使用ViewDragHelper.class處理滑動手勢

SliderPanel.class

private void init(){
    ...
    //1 ViewDragHelper建立
    mDragHelper = ViewDragHelper.create(this, mConfig.getSensitivity(), callback);
    mDragHelper.setMinVelocity(minVel);
    mDragHelper.setEdgeTrackingEnabled(mEdgePosition);

    //2 Setup the dimmer view 新增用於指示滑動過程的View到底層
    mDimView = new View(getContext());
    mDimView.setBackgroundColor(mConfig.getScrimColor());
    mDimView.setAlpha(mConfig.getScrimStartAlpha());
    addView(mDimView);
}

步驟三 在ViewDragHelper.Callback中處理我們的介面的拖動

我們首先明確ViewDragHelper僅僅是處理ParentView與它子View的關係,不會一直遍歷到最頂層的View。ViewDragHelper的捕獲capture是這樣實現的

    @Nullable
    public View findTopChildUnder(int x, int y) {
        final int childCount = mParentView.getChildCount();
        for (int i = childCount - 1; i >= 0; i--) {
            final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i));
            if (x >= child.getLeft() && x < child.getRight()
                    && y >= child.getTop() && y < child.getBottom()) {
                return child;
            }
        }
        return null;
    }

重點在SliderPanel.class的ViewDragHelper.Callback callback的實現,作者實現實現了很多個方向的滑動處理mLeftCallback、mRightCallback、mTopCallback、mBottomCallback、mVerticalCallback、mHorizontalCallback, 我們取mLeftCallback來分析

private ViewDragHelper.Callback mLeftCallback = new ViewDragHelper.Callback() {

    //捕獲View
    @Override
    public boolean tryCaptureView(View child, int pointerId) {
        boolean edgeCase = !mConfig.isEdgeOnly() || mDragHelper.isEdgeTouched(mEdgePosition, pointerId);
        //像前面說的,我們的內容是最上層子View,mDecorView這裡指的是我們的contentView
        return child.getId() == mDecorView.getId() && edgeCase;
    }

    //拖動, 最終是通過view.offsetLeftAndRight(offset)實現移動
    @Override
    public int clampViewPositionHorizontal(View child, int left, int dx) {
        return clamp(left, 0, mScreenWidth);
    }

    //滑動範圍
    @Override
    public int getViewHorizontalDragRange(View child) {
        return mScreenWidth;
    }

    //釋放處理,判斷是滾回螢幕
    @Override
    public void onViewReleased(View releasedChild, float xvel, float yvel) {
        super.onViewReleased(releasedChild, xvel, yvel);

        int left = releasedChild.getLeft();
        int settleLeft = 0;
        int leftThreshold = (int) (getWidth() * mConfig.getDistanceThreshold());
        boolean isVerticalSwiping = Math.abs(yvel) > mConfig.getVelocityThreshold();

        if(xvel > 0){

            if(Math.abs(xvel) > mConfig.getVelocityThreshold() && !isVerticalSwiping){
                settleLeft = mScreenWidth;
            }else if(left > leftThreshold){
                settleLeft = mScreenWidth;
            }

        }else if(xvel == 0){
            if(left > leftThreshold){
                settleLeft = mScreenWidth;
            }
        }
		
        //滾動到left=0(正常佈局) 或者 滾動到left=mScreenWidth(滾出螢幕)關閉Activity
        mDragHelper.settleCapturedViewAt(settleLeft, releasedChild.getTop());
        invalidate();
    }

    //轉換位置百分比,確定指示層的透明度
    @Override
    public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
        super.onViewPositionChanged(changedView, left, top, dx, dy);
        float percent = 1f - ((float)left / (float)mScreenWidth);

        if(mListener != null) mListener.onSlideChange(percent);

        // Update the dimmer alpha
        applyScrim(percent);
    }

    //回撥到Slidr處理Activity狀態
    @Override
    public void onViewDragStateChanged(int state) {
        super.onViewDragStateChanged(state);
        if(mListener != null) mListener.onStateChanged(state);
        switch (state){
            case ViewDragHelper.STATE_IDLE:
                if(mDecorView.getLeft() == 0){
                    // State Open
                    if(mListener != null) mListener.onOpened();
                }else{
                    // State Closed  這裡回撥到Slidr處理activity.finish()
                    if(mListener != null) mListener.onClosed();
                }
                break;
            case ViewDragHelper.STATE_DRAGGING:

                break;
            case ViewDragHelper.STATE_SETTLING:

                break;
        }
    }
};

對於mDragHelper.settleCapturedViewAt(settleLeft, releasedChild.getTop());內部是使用Scroller.class輔助滾動,所以要在SliderPanel中重寫View.computeScroll()

@Override
public void computeScroll() {
    super.computeScroll();
    if(mDragHelper.continueSettling(true)){
        ViewCompat.postInvalidateOnAnimation(this);
    }
}

總結

整體方案如下圖所示

總體來看原理並不複雜, 就是通過ViewDragHelper對View進行拖動。