Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can avoid firing multiple times an onClick event when the user presses the button more than once really quick?

In Android, if the user presses a button multiple times really quick the onClick event is fired multiple times.. which kind of makes sense.

If the onClick method starts a new Activity, the user can open the same Activity multiple times and each instance of the Activity will be piled on top of the stack.

I usually disable the button inside the onClick method (associated to the button) and enable it again a couple of seconds after with the use of a Handler and postDelay.

I don't really like doing it in this way so is there another way of approaching this problem in a more clean way?

like image 503
Héctor Júdez Sapena Avatar asked Nov 13 '22 15:11

Héctor Júdez Sapena


1 Answers

In the Activities case you could also pass an extra for your Intent:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

or

intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

to avoid multiple starts.

Other way is to have a dummy boolean while you're managing the click that prevents multiple clicks.

UPDATE with example:

boolean processingClick = false;
Button b = new Button();
b.setOnClickListener(new View.OnClickListener() {
    @Override public void onClick(View v) {
        if (!processingClick) {
            processingClick = true;

            //your code here

            processingClick = false;
        }
    }
});
like image 128
Aballano Avatar answered Nov 15 '22 05:11

Aballano