I have a problem with my app that if the user clicks the button multiple times quickly, then multiple events are generated before even my dialog holding the button disappear
Here's my version of the accepted answer. It is very similar, but doesn't try to store Views in a Map which I don't think is such a good idea. It also adds a wrap method that could be useful in many situations.
/**
* Implementation of {@link OnClickListener} that ignores subsequent clicks that happen too quickly after the first one.
* To use this class, implement {@link #onSingleClick(View)} instead of {@link OnClickListener#onClick(View)}.
*/
public abstract class OnSingleClickListener implements OnClickListener {
private static final String TAG = OnSingleClickListener.class.getSimpleName();
private static final long MIN_DELAY_MS = 500;
private long mLastClickTime;
@Override
public final void onClick(View v) {
long lastClickTime = mLastClickTime;
long now = System.currentTimeMillis();
mLastClickTime = now;
if (now - lastClickTime < MIN_DELAY_MS) {
// Too fast: ignore
if (Config.LOGD) Log.d(TAG, "onClick Clicked too quickly: ignored");
} else {
// Register the click
onSingleClick(v);
}
}
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
public abstract void onSingleClick(View v);
/**
* Wraps an {@link OnClickListener} into an {@link OnSingleClickListener}.
* The argument's {@link OnClickListener#onClick(View)} method will be called when a single click is registered.
*
* @param onClickListener The listener to wrap.
* @return the wrapped listener.
*/
public static OnClickListener wrap(final OnClickListener onClickListener) {
return new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
onClickListener.onClick(v);
}
};
}
}