Android之簡易滑動后退實現(xiàn)方案

前言

滑動后退,很多的app都有的,做得好的如微信,知乎,簡書等等,這種效果,我也是挺喜歡的,網(wǎng)上有開源框架SwipeBackLayout可以實現(xiàn),用法可以參考別人的文章:帶你使用SwipeBackLayout和SwipeBackActivity。

效果

效果圖

簡單實現(xiàn)

實現(xiàn)很簡單,不多說,直接看代碼吧

B Activity滑動退出時動畫:
anim/push_right_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set
  xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:interpolator="@android:anim/decelerate_interpolator" android:duration="400" android:fromXDelta="0.0" android:toXDelta="100.0%p" />
</set>

A Activity在B Activity退出時A Activity進入的動畫
anim/zoom_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:duration="400"
        android:fillBefore="false"
        android:fromXScale="0.9"
        android:fromYScale="0.9"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:pivotX="50.0%"
        android:pivotY="50.0%"
        android:toXScale="1.0"
        android:toYScale="1.0" />
    <alpha
        android:duration="400"
        android:fromAlpha="0.1"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:toAlpha="1.0" />
</set>

這里實現(xiàn)了GestureDetector對滑動進行監(jiān)聽

private void initDetector() {
        if (!isSwipeBack)
            return;
        mDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                float f2 = e1.getX() - e2.getX();
                float f1 = f2 / (e1.getY() - e2.getY());
                if ((f1 > 3.0F) || (f1 < -3.0F)) {//右滑后退
                    if (f2 <= -160.0F) {
                        finish();
                        overridePendingTransition(R.anim.zoom_out, R.anim.push_right_out); //注意,需要在finish后,否則不起作用
                        return true;
                    }

                }
                return false;
            }
        });
    }
    private boolean isSwipeBack = true;
    public void setSwipeBack(boolean swipeBack) { //設置是否需要啟用右滑后退,默認啟用
        isSwipeBack = swipeBack;
    }

    public boolean dispatchTouchEvent(MotionEvent event) {
        if (isSwipeBack && (mDetector != null) && (event != null)) {
            if (mDetector.onTouchEvent(event)) return true;//如果處理了就直接return回去
        }
        return super.dispatchTouchEvent(event);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容