package com.jiangjiesheng.ges;
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View.OnTouchListener;
import android.widget.Toast;
/**
* 类说明 :手势检测
*
* @author 作者 江节胜 E-mail:dev@jiangjiesheng.cn
* @version 创建时间:2016年8月23日 下午4:22:19
*
*/
public class MainActivity extends Activity {
OnTouchListener mOnTouchListener;
// 定义手势检测器实例
GestureDetector detector;
boolean First = true;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//第一个参数Context(传入Activity本身可能为空)
detector = new GestureDetector(this, new OnGestureListener() {//import //android.view.GestureDetector.OnGestureListener;
private float minMove = 20;//使用时调为30
private float minVelocity = 0;
private float beginX;
private float endX;
private float beginY;
private float endY;
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
/**
* 手指在屏幕上时(未离开)
*/
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
/**
* 手指离开屏幕时
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
/**
* 注意:手指按下开始不停滑动时,开始位置是一直不变的
*
*/
// if (First == true) {
// Log.i("test", "移动距离 First == true");
// beginX = e1.getX();
// beginY = e1.getY();
// }
endX = e2.getX();
beginX = e1.getX();
beginY = e1.getY();
endY = e2.getY();
if (beginX - endX > minMove
&& Math.abs(velocityX) > minVelocity) {
// 左滑
showToast(velocityX + "左滑");
} else if (endX - beginX > minMove
&& Math.abs(velocityX) > minVelocity) { // 右滑
showToast(velocityX + "右滑");
} else if (beginY - endY > minMove
&& Math.abs(velocityY) > minVelocity) { // 上滑
showToast(velocityX + "上滑");
} else if (endY - beginY > minMove
&& Math.abs(velocityY) > minVelocity) { // 下滑
showToast(velocityX + "下滑");
}
// beginX = endX;//改变起始位置
// beginY = endY;//改变起始位置
// First = false;
return false;
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
});
setContentView(R.layout.fragment_main);
}
/**
*如果在非Activity中,无onTouchEvent 方法。可以在布局的跟节点设置id(先new出detector对象)
*
* findViewById(R.id.XXX).setOnTouchListener(
* new OnTouchListener() {
*
* @Override
* public boolean onTouch(View v, MotionEvent event) {
* // TODO Auto-generated method stub
* return detector.onTouchEvent(event);
* }
* });
*
**/
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return detector.onTouchEvent(event);
}
Toast mToast;
private void showToast(String msg) {
if (mToast == null) {
mToast = Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_SHORT);
} else {
mToast.setText(msg);
}
mToast.show();
}
}