前言
滑动后退,很多的app都有的,做得好的如微信,知乎,简书等等,这种效果,我也是挺喜欢的,网上有开源框架SwipeBackLayout可以实现,用法可以参考别人的文章:带你使用SwipeBackLayout和SwipeBackActivity。
效果
效果图简单实现
实现很简单,不多说,直接看代码吧
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>
这里实现了GestureDetector对滑动进行监听
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);
}
网友评论