gpt4 book ai didi

android - View 的 Ontouch 方法中的单点触摸检测

转载 作者:IT老高 更新时间:2023-10-28 23:26:40 24 4
gpt4 key购买 nike

我需要在我的自定义 View 的 ontouch 方法中进行单点触摸检测。我尝试在 ACTION-DOWN 和 ACTION-UP 和 ACTION-UP 中获取 x 和 y 值.

我的代码如下

@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!mSupportsZoom && !mSupportsPan) return false;

mScaleDetector.onTouchEvent(ev);

final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();

mLastTouchX = x; //here i get x and y values in action down
mLastTouchY = y;
mActivePointerId = ev.getPointerId(0);

break;
}

case MotionEvent.ACTION_MOVE: {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);

if (mSupportsPan && !mScaleDetector.isInProgress()) {
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;

mPosX += dx;
mPosY += dy;
//mFocusX = mPosX;
//mFocusY = mPosY;

invalidate();
}

mLastTouchX = x;
mLastTouchY = y;

break;
}

case MotionEvent.ACTION_UP: {

final float x = ev.getX();
final float y = ev.getY();

touchupX=x; //here is get x and y values at action up
touchupY=y;

if(mLastTouchX == touchupX && mLastTouchY == touchupY){ //my condition if both the x and y values are same .

PinchZoomPanActivity2.tapped1(this.getContext(), 100); //my method if the singletap is detected

}
else{

}

mActivePointerId = INVALID_POINTER_ID;

break;
}

case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}

case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK)
>> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {

final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
}
break;
}
}

return true;
}

但我无法完成它。我的意思是在每次操作时都会调用我的方法。即使 actionup 和 actiondown 的 x 和 y 值不相同。而且我认为当我们用手指在屏幕上触摸时,我还需要为单击设置一些范围。谁能给我一些建议?

最佳答案

要在 android 中检测 Single Tap 和 Double Tap,我使用以下方法:

class GestureTap extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.i("onDoubleTap :", "" + e.getAction());
return true;
}

@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Log.i("onSingleTap :", "" + e.getAction());
return true;
}
}

在 GestureDetector 的构造函数中使用它:

detector = new GestureDetector(this, new GestureTap());

并在onTouch监听器中添加如下代码

@Override
public boolean onTouchEvent(MotionEvent event) {

detector.onTouchEvent(event);

return true;
}

关于android - View 的 Ontouch 方法中的单点触摸检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com