javaandroidandroid-studio-3.0timedelaypostdelayed

How to detect taps on a button whilst a delay caused by postDelayed Handler


I want to solve a problem that I have been trying to do so the last couple of days but I don't have that much experience and I couldn't find the solution anywhere else.

Anyway, in my app I have a button in which I have implemented the onClickClistener in order to respond to touch and inside that I have added a Handler which adds a delay and after that some code is being executed. My problem is that I want to detect any tap of the button whilst the delay is happening and the postDelayed function doesn't allow me to do so. How can I actually do that? I've posted my code that is related on that. Thanks in advance!

P.S(I don't mind not using this postDelayed thing.)

Button button = findViewById(R.id.myButtonId);

button.setOnClickListener(new View.OnClickListener){
 @Override
        public void onClick(View v) {
            .......
            
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                
                @Override
                public void run() {
                  
                //Do some thing after the delay
                
               }
            }, randomDelay);
            
            //Do other things
        }
    });

Solution

  • boolean previousTapDetected;
    ...
    button.setOnClickListener(new View.OnClickListener){
     @Override
            public void onClick(View v) {
                .......
                if(previousTapDetected) {
                    //We got a tap during the delay
                }
                Handler handler = new Handler();
                previousTapDetected = true;
                handler.postDelayed(new Runnable() {
    
                    @Override
                    public void run() {
                        previousTapDetected = false;
                    //Do some thing after the delay
    
                   }
                }, randomDelay);
    
                //Do other things
            }
        });