我希望可以在安卓手机上捕获手指移动的方向。如果用户沿着上下左右滑动手指,我需要捕获这个方向。如何找到这个方向?谢谢。
我想在安卓触摸手机上捕捉手指的移动方向。 如果用户向上/向下/向左/向右滑动手指,我希望能够捕捉这个方向。 我该如何寻找这个方向?谢谢。
我想在安卓触摸手机上捕捉手指的移动方向。 如果用户向上/向下/向左/向右滑动手指,我希望能够捕捉这个方向。 我该如何寻找这个方向?谢谢。
实现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";
}
}
}
您最好的选择是处理从View.OnTouchListener()回调中获取的MotionEvent。运动事件通过其操作属性跟踪您当前与视图的交互方式。
我想您可以通过检查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
if(Math.abs(deltaY)>Math.abs(deltaX))
。 - tibbiprivate 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
}