首先如果有类似需求的话,我们可能会首先想到onTouchEvent方法.然在这个方法中判断在x轴上移动的距离,然后进行相关的操作.不过android给我们提供了更好的选择:GestureDetector,通过这个对象.然后我们可以更简单的来识别各种手势,结合实际开发需要,我们把对屏幕右划的操作都放在BaseActivity中来写.这样子类只需要继承一下.然后调用一个方法来设置是否需要右划退出的功能就行了
BaseActivity.java
package com.example.testactivityinoutanimation;
import com.example.testactivityinoutanimation.customeclass.BackGestureListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
public class BaseActivity extends Activity {
/** 手势监听 */
GestureDetector mGestureDetector;
/** 是否需要监听手势关闭功能 */
private boolean mNeedBackGesture = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
initGestureDetector();
}
private void initGestureDetector() {
if (mGestureDetector == null) {
mGestureDetector = new GestureDetector(getApplicationContext(),
new BackGestureListener(this));
}
}
/* (non-Javadoc)
* touch手势分发
* @see android.app.Activity#dispatchTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
if (mNeedBackGesture) {
return mGestureDetector.onTouchEvent(ev)
|| super.dispatchTouchEvent(ev);
}
return super.dispatchTouchEvent(ev);
}
/*
* 设置是否进行手势监听
*/
public final void setNeedBackGesture(boolean mNeedBackGesture) {
this.mNeedBackGesture = mNeedBackGesture;
}
}
BackGestureListener.class
package com.example.testactivityinoutanimation.customeclass;
import android.app.Activity;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
/**
* @author imgod
*自定义一个类来实现OnGestureListener 手势监听
*/
public class BackGestureListener implements OnGestureListener{
private Activity mc;
public BackGestureListener(Activity context) {
// TODO Auto-generated constructor stub
mc = context;
}
@Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
float arg3) {
// 已经往右滑动超过100px并且上下滑动不超过60px
if((arg1.getX()-arg0.getX())>100&&(Math.abs(arg0.getY()-arg1.getY())<60)) {
mc.onBackPressed();
}
return false;
}
@Override
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
}
这样我们的其他Activity就可以很方便的只需要设置一下是否需紧要手势滑动就可以右划推出了.