private VelocityTracker mVt = null;
private int mMoveCount = 0;
private float mVx = 0;
private float mVy = 0;
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// 手指按下
mVt = VelocityTracker.obtain(); // 建立一个新的对象
mVt.addMovement(event); // 增加一个采样点
LogUtil.d("action down------------------------------------------vt====");
break;
case MotionEvent.ACTION_MOVE:
// 手指移动
event.getX();
event.getY();
// 添加采样点
LogUtil.d("action move------------------------------------------mMoveCount======"
+ mMoveCount++);
mVt.addMovement(event);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE:
// 触摸事件结束
LogUtil.d("action up------------------------------------------");
// 设置速度的时间单位 1代表每毫秒移动多少像素 1000代表每秒移动多少像素
// 这个方法在获得速度之前必须要设置
mVt.clear();// 清空
mVt.recycle();// 回收vt对象的内存
break;
}
mVt.computeCurrentVelocity(1000);
mVx = mVt.getXVelocity();// 得到当前手指在这一点移动的速度
mVy = mVt.getYVelocity();// 速度分为了x和y轴两个方向的速度
int dir = judgeDir(mVx, mVy);
if (mMoveCount==2) {
if (dir == 1) {// right
if (mIsConfiged) {
currentToRightAnimation();
LogUtil.d("right right right right right right right right ");
}else{
mMoveCount=0;
}
} else if (dir == 2) {// left
if (mIsConfiged) {
currentToLeftAnimation();
LogUtil.d("------------------left------------left------------left");
}else{
mMoveCount=0;
}
} else if (dir == 3) {// down
currentToDownAnimation();
LogUtil.d("down down down down down down down ");
} else if (dir == 4) {// up
currentToUpAnimation();
LogUtil.d("up up up up up up up up ");
}
LogUtil.d("dir=================================================="
+ dir);
}
if(dir==0){
mMoveCount=0;
}
return true;
}
private int judgeDir(float vx, float vy) {
if (vx >= 0 && Math.abs(vy / vx) <= Math.sqrt(3) / 3) // 小于30度
{
// img1.setImageResource(R.drawable.ic_launcher);
// 方向是正右方 1
return 1;
} else if (vx < 0 && Math.abs(vy / vx) <= Math.sqrt(3) / 3) {
// img2.setImageResource(R.drawable.ic_launcher);
// 方向是正左方 2
return 2;
} else if (vy > 0 && Math.abs(vx / vy) <= Math.sqrt(3) / 3) {
// img3.setImageResource(R.drawable.ic_launcher);
// 方向是正下方 3
return 3;
} else if (vy < 0 && Math.abs(vx / vy) <= Math.sqrt(3) / 3) {
// img4.setImageResource(R.drawable.ic_launcher);
// 方向是正上方 4
return 4;
}
return 0;
}
根据移动速度方向判断手势方向
最新推荐文章于 2022-06-01 14:42:50 发布
该博客介绍了如何使用VelocityTracker来检测用户的触摸移动事件,通过计算手指移动的速度和方向,判断手势是向右、左、下还是上。在ACTION_DOWN、ACTION_MOVE和ACTION_UP等触摸事件中,收集并分析移动速度,最终确定手势方向。
摘要由CSDN通过智能技术生成