5

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?

1
  • ebable/disable the button seems good to me Commented Dec 17, 2012 at 10:48

3 Answers 3

1

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; } } }); 
Sign up to request clarification or add additional context in comments.

3 Comments

The FLAG_ACTIVITY_CLEAR_TOP will probably work in combination with FLAG_ACTIVITY_SINGLE_TOP.. otherwise the activity is re-created with each onclick event. The dummy boolean approach works perfect, though I was expecting some kind of control from the Android API.
Yeah, me too. I think the problem here is the little delay in the startActivity method, but I don't know if there's something that the platform could do.
could someone please elaborate on how the dummy boolean method would be achieved? any example code? cheers.
0

clean way:

After you click the button, if the thing you want to invoke is null, invoke it, otherwise, don't.

Comments

0

Make a Method for all Buttons in the Actitivty:

public void enableButtons(boolean doit){ bXXX.setClickable(doit); ... ... } 

If using "implement OnClickListener"

@Override public void onClick(View view) { enableButtons(false); switch (view.getId()) { case R.id.xxx: doWhatYouWant(); break; ... ... } } 

OnResume activate your Buttons again...

@Override protected void onResume() { super.onResume(); enableButtons(true); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.