通过右滑手势关闭当前Activity,这个是很常见的需求,网上参考过几篇文章发现实现都比较复杂,他们大多自己另外写了个Layout,然后这个Layout当做页面的布局,经测试其实有更简单一点的方法,写个BaseActivity,其他Activity继承即可。这里给出代码,大家测试看看。有问题回馈一下,谢谢!
package com.figo.study.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class BaseActivity extends Activity implements View.OnTouchListener, GestureDetector.OnGestureListener {
GestureDetector mGestureDetector;
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGestureDetector = new GestureDetector((GestureDetector.OnGestureListener) this);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
mGestureDetector.onTouchEvent(ev);
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
private int verticalMinDistance = 20;
private int minVelocity = 0;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(e2.getY() - e1.getY()) > 200) {//这里是避免有scroolview的页面上划也关闭
return false;
}
if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {//左滑操作
} else if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {//右滑操作
this.finish();
}
return false;
}
}