[英]Android: OnTouchListener.OnTouch not called in multiTouch
[英]Ontouch event of OnTouchListener gets called twice in android
我正在创建一个应用程序,其中在运行时给定的两个点之间生成一条线。
我看到的问题是每次点击我的模拟器时onTouch()
被调用两次。 我知道检查了两个操作( ACTION_DOWN
和ACTION_UP
)。 但我希望我的应用程序只调用一次onTouch()
。 请给我一些想法。 这是我使用的代码:
SurfaceView surfaceview = new SurfaceView(getContext());
SurfaceHolder h = surfaceview.getHolder();
int action = event.getActionMasked();
synchronized(h) {
if (action == MotionEvent.ACTION_DOWN && action!=MotionEvent.ACTION_CANCEL)// && flag==true)
{
Log.d("TouchView","ACTION_DOWN ");
Point pointer = new Point();
pointer.x = (int) event.getX();
pointer.y = (int) event.getY();
touchPoint.add(pointer);
view.invalidate();
Log.d("MotionEvent.ACTION_DOWN", "point: " + pointer);
action = MotionEvent.ACTION_CANCEL;
flag = false;
}
else if(action == MotionEvent.ACTION_UP && action!=MotionEvent.ACTION_CANCEL)// && flag==true)
{
Log.d("TouchView","ACTION_UP");
Point pointer = new Point();
pointer.x = (int) event.getX();
pointer.y = (int) event.getY();
touchPoint.add(pointer);
view.invalidate();
Log.d("MotionEvent.ACTION_UP", "point: " + pointer);
action = MotionEvent.ACTION_CANCEL;
flag = false;
}
else return false;
}
touchListener将被要求每MotionEvent.ACTION_DOWN
, MotionEvent.ACTION_UP
和MotionEvent.ACTION_MOVE
。 所以如果你只想执行一次代码,即MotionEvent.ACTION_DOWN
然后在里面
onTouch()
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//your code
}
或者只使用 onClickListener:
myButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
//do what you gotta do
}
});
有时在同一个父级下处理许多视图会导致多次调用 onTouch(如果它们彼此之上),我的解决方案是
onTouch{ ... if(event.getAction() == MotionEvent.ACTION_DOWN && isTouchEnabled()){ enableTouch(false); //add your code here //then enableTouch at the end this.postDelayed(new Runnable() { @Override public void run() { enableTouch(true); } }, 500); } add static variable touch private static boolean enabled = true; private void enableTouch(boolean enabled){ this.enabled = enabled; } private boolean isTouchEnabled(){ return enabled; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.