OnTouchListener的Ontouch事件在android中被调用两次


73

我正在创建一个应用程序,其中在运行时给定的两点之间生成一条线。
我看到的问题是,onTouch()每次在模拟器上单击都会调用两次。我知道两个动作(ACTION_DOWNACTION_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;
}

Answers:


172

touchListener将呼吁联合国各MotionEvent.ACTION_DOWNMotionEvent.ACTION_UPMotionEvent.ACTION_MOVE。因此,如果您只想执行一次代码,即MotionEvent.ACTION_DOWN 在内部执行

onTouch()
 if (event.getAction() == MotionEvent.ACTION_DOWN) {
//your code 
}

1
感谢您的提示!认为按钮/链接上的触摸就像两次单击操作一样。
asgs

1
@raja自己解释int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN){ ...}
小型Mayhé

对我来说,它被叫过4次了,无论如何还是两次感谢
Farido mastr

4

或者只使用onClickListener:

        myButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                //do what you gotta do
            }
        });

Dpedrinha,使用onTouchListener的一个原因是在微调器上注册点击,因为onClickListener可能不与微调器一起使用。
卡尔

1
如果不需要MotionEvent数据的额外信息,这是最佳解决方案。
SMBiggs

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;
    }

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.