Preventing Duplicate Actions from Rapid Taps in Android
A straightforward pattern for preventing duplicate action triggers when users tap buttons multiple times in quick succession.
A common issue in Android applications: a user taps a button, the response is not instantaneous, and they tap again. Each tap triggers the action, potentially launching duplicate Activities or firing redundant network requests.
Solution
Guard the click handler with a boolean flag:
private boolean isClicked = false;
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!isClicked) {
isClicked = true;
startActivity(new Intent(this, NextActivity.class));
}
}
});
Reset the flag when the Activity resumes, allowing the button to be used again upon return:
@Override
protected void onResume() {
super.onResume();
isClicked = false;
}
This is a lightweight pattern that prevents a surprisingly common class of bugs in production applications.