I have looked at the answers here - Android Preventing Double Click On A Button
and implemented qezt\'s solution like and I\'ve tried setEnabled(false)
like so
I am doing like this it works very well.
public abstract class OnOneOffClickListener implements View.OnClickListener {
private static final long MIN_CLICK_INTERVAL=600;
private long mLastClickTime;
public static boolean isViewClicked = false;
public abstract void onSingleClick(View v);
@Override
public final void onClick(View v) {
long currentClickTime=SystemClock.uptimeMillis();
long elapsedTime=currentClickTime-mLastClickTime;
mLastClickTime=currentClickTime;
if(elapsedTime<=MIN_CLICK_INTERVAL)
return;
if(!isViewClicked){
isViewClicked = true;
startTimer();
} else {
return;
}
onSingleClick(v);
}
/**
* This method delays simultaneous touch events of multiple views.
*/
private void startTimer() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
isViewClicked = false;
}
}, 600);
}
}
You can use this method. By using post delay you can take care for double click events.
void debounceEffectForClick(View view) {
view.setClickable(false);
view.postDelayed(new Runnable() {
@Override
public void run() {
view.setClickable(true);
}
}, 500);
}
Set the launchMode of the activity in manifest as singleTop
<activity
android:name="com.example.MainActivity"
android:screenOrientation="portrait"
android:launchMode="singleTop"/>
Qezt solution is already fine. But if you want to prevent super fast double-click, then you simply reduce the threshhold
// half a second
if (SystemClock.elapsedRealtime() - doneButtonClickTime < 500) {
return;
}
// or 100ms (1/10 of second)
if (SystemClock.elapsedRealtime() - doneButtonClickTime < 100) {
return;
}
Kotlin short version:
private var lastClickTime: Long = 0
//in click listener
if (SystemClock.elapsedRealtime() - lastClickTime < 1000) {
return
}
lastClickTime = SystemClock.elapsedRealtime()
Probably not most efficient, but minimal inversive:
...
onClick(View v) {
MultiClickPreventer.preventMultiClick(v);
//your op here
}
...
public class MultiClickPreventer {
private static final long DELAY_IN_MS = 500;
public static void preventMultiClick(final View view) {
if (!view.isClickable()) {
return;
}
view.setClickable(false);
view.postDelayed(new Runnable() {
@Override
public void run() {
view.setClickable(true);
}
}, DELAY_IN_MS);
}
}