Skip to content

Instantly share code, notes, and snippets.

@mrhether
Created May 9, 2016 19:46
Show Gist options
  • Save mrhether/b25b2a8816faf7fe836e18d3e1f1ec9d to your computer and use it in GitHub Desktop.
Save mrhether/b25b2a8816faf7fe836e18d3e1f1ec9d to your computer and use it in GitHub Desktop.
OnSingleClickListener
/**
* Implementation of {@link OnClickListener} that ignores subsequent clicks that happen too quickly after the first one.<br/>
* 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}.<br/>
* 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);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment