3

I have a button like a switch where I am trying to setClickable(false) after I click it so that only the first click will be handled (additional clicks are ignored in the case of accidental double-clicks/multiple-clicks).

Here is a similar code:

Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Button.setClickable(false);
        //do other things
    }
});

Then eventually, I have a code somewhere where I will reset the clickable to true, depending on a state variable, so I can switch-off.

The problem is when I click the button very quickly, it seems the succeeding clicks are still handled. Is there a delay to the effects of setClickable()?

Also, I have read about using setEnabled(false) instead, but I cannot use it in my case. I need the button to still be enabled but not clickable.

martinC
  • 39
  • 2

3 Answers3

1

Judging from your comment you probably need something like this.

  Boolean SWITCH_ON = false;

  Button.setOnClickListener(new OnClickListener() {
 
  public void onClick(View v) {
         if(!SWITCH_ON ){
                  SWITCH_ON = true;   
         }
    }
 });

Button.setOnLongClickListener(new View.OnLongClickListener() {

public boolean onLongClick(View v) {
    
   if(SWITCH_ON ){
      // do your task for long click here ...SWITCH_ON 
    }
   return true;
}
});
Rohaitas Tanoli
  • 624
  • 4
  • 16
0

You can use button.setEnabled(false); within your onClick method to disable the button.

Disabled buttons don't trigger the onClick method, and you can easily re-enable it with button.setEnabled(true); when needed.

isaaaaame
  • 460
  • 4
  • 9
  • I cannot disable the button. I need the button to still be enabled, but not clickable. The reason, which I did not state yet, is that the button needs to be long-clickable when the switch is ON. – martinC Sep 01 '20 at 09:50
0

You could add another variable named buttonEnabled or so and initialize it with true. Then in the onclick do this:

Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Button.setClickable(false);
        if(buttonEnabled) {
            //do other things
        }
        buttonEnabled = false;
    }
});

Note that you need to change the variable to if you want to reactivate it

McSlinPlay
  • 449
  • 2
  • 13