Android: Prevent multiple onClick events on a button (that has been disabled)
android, java, user-interface
Solution
You could set a boolean variable to true when the button is clicked and set it to false when you're done processing the click.
This way you can ignore multiple clicks and not having to disable the button possibly avoiding annoying flickering of the button.
boolean processClick=true;
someButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(processClick)
{
someButton.setEnabled(false);
someButton.setClickable(false);
someButton.setVisibility(View.GONE);
performTaskOnce();
}
processClick=false;
}
});
private void performTaskOnce() {
Log.i("myapp", "Performing task");
//Do something nontrivial that takes a few ms (like changing the view hierarchy)
}
Problem
A button triggers an action that should only be invoked once. The button is disabled and hidden in the onClick handler before the action is performed: ``` someButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { someButton.setEnabled(false); someButton.setClickable(false); someButton.setVisibility(View.GONE); performTaskOnce(); } }); private void performTaskOnce() { Log.i("myapp", "Performing task"); //Do something nontrivial that takes a few ms (like changing the view hierarchy) } ``` Even though the button is disabled immediately, it is nonetheless possible to trigger multiple "onClick" events by tapping multiple times very quickly. (i.e. `performTaskOnce` is called multiple times). Is seems that the onClick events are queued before the the button is actually disabled. I could fix the problem by checking in every single onClick handle whether the corresponding button is already disabled but that seems like a hack. Is there any better way to avoid this issue? The problem occurs on Android 2.3.6, I cannot reproduce it on Android 4.0.3. But given the rarity of 4.x devices it is not an option to exclude older devices.