Ontouch event of OnTouchListener gets called twice in android

后端 未结 3 1952
醉梦人生
醉梦人生 2020-12-24 10:03

I am creating an appliction in which a line gets generated between two points given at runtime.
The problem that I see is that onTouch() is called twice for

相关标签:
3条回答
  • 2020-12-24 10:42

    Sometimes dealing with many views under the same parent cause the onTouch called many times (if they're above each other) the solution for me was

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

    0 讨论(0)
  • 2020-12-24 10:48

    touchListener will be called for every MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP, and MotionEvent.ACTION_MOVE . so if you want to execute code only once , ie MotionEvent.ACTION_DOWN then inside

    onTouch()
     if (event.getAction() == MotionEvent.ACTION_DOWN) {
    //your code 
    }
    
    0 讨论(0)
  • 2020-12-24 10:57

    Or just use onClickListener:

            myButton.setOnClickListener(new Button.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //do what you gotta do
                }
            });
    
    0 讨论(0)
提交回复
热议问题