我正在创建一个应用程序,其中在运行时给出的两个点之间生成一条线
我看到的问题是,在我的模拟器上每次点击都会调用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;
}
答案 0 :(得分:146)
将为每个MotionEvent.ACTION_DOWN
,MotionEvent.ACTION_UP
和MotionEvent.ACTION_MOVE
调用touchListener。所以如果你只想执行一次代码,即MotionEvent.ACTION_DOWN
onTouch()
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//your code
}
答案 1 :(得分:3)
或者只使用onClickListener:
myButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
//do what you gotta do
}
});
答案 2 :(得分:0)
有时候在同一个父对象下处理多个视图会导致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;
}