我想捕捉Android触控手机上的手指移动方向。如果用户向上/向下/向左/向右滑动手指,我想捕获此方向。我怎么能找到这个?感谢。
答案 0 :(得分:43)
实现onTouchEvent(),并根据用户按下并抬起的位置计算dx和dy。您可以使用这些值来确定移动的方向。
float x1, x2, y1, y2, dx, dy;
String direction;
switch(event.getAction()) {
case(MotionEvent.ACTION_DOWN):
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
// Use dx and dy to determine the direction of the move
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0)
direction = "right";
else
direction = "left";
} else {
if(dy>0)
direction = "down";
else
direction = "up";
}
}
}
答案 1 :(得分:10)
最好的办法是处理从View.OnTouchListener()回调中获得的MotionEvent。运动事件会跟踪您当前如何通过其动作属性与View进行交互。
我想你可以通过检查MotionEvents的动作属性和动作事件发生位置的x / y值来计算某人滑动手指的方向。
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
oldX= event.getX();
oldY= event.getY();
break;
case MotionEvent.ACTION_MOVE:
int newX = motionEvent.getX();
int newY = motionEvent.getY();
int deltaX = oldX - newX;
int deltaY = oldY - newY;
if(Math.abs(deltaY)>Math.abs(deltaX))
//Motion in Y direction.
else
// Motion in X direction.
break;
}
MotionEvent对象上还有许多其他方法可供使用: http://developer.android.com/reference/android/view/MotionEvent.html
答案 2 :(得分:2)
我认为最好使用VelocityTracker
的修改示例private var mVelocityTracker: VelocityTracker? = null
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
// Reset the velocity tracker back to its initial state.
mVelocityTracker?.clear()
// If necessary retrieve a new VelocityTracker object to watch the
// velocity of a motion.
mVelocityTracker = mVelocityTracker ?: VelocityTracker.obtain()
// Add a user's movement to the tracker.
mVelocityTracker?.addMovement(event)
}
MotionEvent.ACTION_MOVE -> {
mVelocityTracker?.run {
val pointerId: Int = event.getPointerId(event.actionIndex)
addMovement(event)
// When you want to determine the velocity, call
// computeCurrentVelocity(). Then call getXVelocity()
// and getYVelocity() to retrieve the velocity for each pointer ID.
computeCurrentVelocity(1000)
val xVelocity = getXVelocity(pointerId)
val yVelocity = getYVelocity(pointerId)
if (abs(xVelocity) > abs(yVelocity))
if (xVelocity > 0)
// right
else
// left
else
if (yVelocity > 0)
// down
else
// up
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
// Return a VelocityTracker object back to be re-used by others.
mVelocityTracker?.recycle()
mVelocityTracker = null
}
}
return true
}