前言
滑動(dòng)后退,很多的app都有的蜻韭,做得好的如微信悼尾,知乎柿扣,簡書等等,這種效果诀豁,我也是挺喜歡的窄刘,網(wǎng)上有開源框架SwipeBackLayout可以實(shí)現(xiàn),用法可以參考別人的文章:帶你使用SwipeBackLayout和SwipeBackActivity舷胜。
效果
簡單實(shí)現(xiàn)
實(shí)現(xiàn)很簡單娩践,不多說,直接看代碼吧
B Activity滑動(dòng)退出時(shí)動(dòng)畫:
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退出時(shí)A Activity進(jìn)入的動(dòng)畫
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>
這里實(shí)現(xiàn)了GestureDetector對(duì)滑動(dòng)進(jìn)行監(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) { //設(shè)置是否需要啟用右滑后退,默認(rèn)啟用
isSwipeBack = swipeBack;
}
public boolean dispatchTouchEvent(MotionEvent event) {
if (isSwipeBack && (mDetector != null) && (event != null)) {
if (mDetector.onTouchEvent(event)) return true;//如果處理了就直接return回去
}
return super.dispatchTouchEvent(event);
}