237

What is the best way to prevent double clicks on a button in Android?

4
  • 3
    See qezt's solution only it fully workable Nov 4, 2014 at 18:44
  • 3
    qezt's solution should have been accepted, so that people who visit this page, know drawback of using setEnabled(false). Oct 10, 2016 at 19:56
  • You can try my library, using last-click-time solution: github.com/RexLKW/SClick
    – Rex Lam
    Oct 15, 2016 at 0:10
  • 2
    @Androider please change your best answer
    – Amir133
    Dec 5, 2018 at 5:33

57 Answers 57

448

saving a last click time when clicking will prevent this problem.

i.e.

private long mLastClickTime = 0;

...

// inside onCreate or so:

findViewById(R.id.button).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // mis-clicking prevention, using threshold of 1000 ms
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        // do your magic here
    }
}
23
  • 28
    This is the only solution that actually prevents a double click. I just spent an hour trying all of the others since this method is pretty clunky, but none of them could prevent a quick double tap of a view except this one. Google please fix this :)
    – ashishduh
    Jan 27, 2014 at 23:26
  • 7
    This solution works fine.This solution also works when you have multiple buttons on the screen and you want to click only single button at time.
    – void
    Mar 6, 2014 at 7:41
  • 17
    This does not completely prevent double clicks if you do double click fast enough.
    – LHA
    Sep 18, 2014 at 22:34
  • 4
    Best answer, it should be on top Nov 4, 2014 at 18:43
  • 3
    This solution should be the right answer... setEnabled(false) is not enough.
    – heloisasim
    Oct 2, 2015 at 19:08
109

Disable the button with setEnabled(false) until it is safe for the user to click it again.

13
  • 57
    setEnabled(false) doesn't seem to work "fast" enough. I've set up a View.OnClickListener.onClick(view) for a button. First thing I do in onClick() is write a log-statement, 2nd statement is button.setEnabled(false). When fast-double-clicking in the emulator I see the log-statement appear twice! Even when adding a setClickable(false) right after that, the log-statement appears twice. Jun 24, 2011 at 8:41
  • 108
    I had a similar problem. According to one helpful gentleman, Android actually queues the clicks, so it doesnt matter how fast or slow your onClick() code executes; only how fast you click the button. Ie. You may have already disabled the button, but the click queue has already been filled with two or three clicks and disabling the button has no effect on the delivery of queued clicks. (although maybe it should?)
    – Nick
    May 22, 2012 at 16:03
  • 3
    That rare moment when you see 'someone' gives an exact answer and not abstraaaaaaaact answers to the question being asked.. :P
    – Rahul
    Mar 6, 2014 at 16:22
  • 1
    this is not always the right solution. If your onClick is expensive operation, then the button will not disable fast enough. The full-proof solution IMHO is to use the last click time, but also disable the button to avoid user tapping on it again if you expect the operation to last a while (such as login).
    – Sarang
    Oct 9, 2014 at 17:55
  • 4
    You should also use view.cancelPendingInputEvents() to prevent uncaught clicks Jan 25, 2019 at 14:13
66

My solution is

package com.shuai.view;

import android.os.SystemClock;
import android.view.View;

/**
 * 处理快速在某个控件上双击2次(或多次)会导致onClick被触发2次(或多次)的问题
 * 通过判断2次click事件的时间间隔进行过滤
 * 
 * 子类通过实现{@link #onSingleClick}响应click事件
 */
public abstract class OnSingleClickListener implements View.OnClickListener {
    /**
     * 最短click事件的时间间隔
     */
    private static final long MIN_CLICK_INTERVAL=600;
    /**
     * 上次click的时间
     */
    private long mLastClickTime;

    /**
     * click响应函数
     * @param v The view that was clicked.
     */
    public abstract void onSingleClick(View v);

    @Override
    public final void onClick(View v) {
        long currentClickTime=SystemClock.uptimeMillis();
        long elapsedTime=currentClickTime-mLastClickTime;
        //有可能2次连击,也有可能3连击,保证mLastClickTime记录的总是上次click的时间
        mLastClickTime=currentClickTime;

        if(elapsedTime<=MIN_CLICK_INTERVAL)
            return;

        onSingleClick(v);        
    }

}

Usage is similar as OnClickListener but override onSingleClick() instead:

mTextView.setOnClickListener(new OnSingleClickListener() {
            @Override
            public void onSingleClick(View v) {
                if (DEBUG)
                    Log.i("TAG", "onclick!");
            }
     };
9
  • 1
    Easy and perfect to automatically prevent double touches. Jan 16, 2014 at 11:27
  • 1
    This does not completely prevent double clicks if you do double click fast enough.
    – LHA
    Sep 18, 2014 at 22:34
  • 1
    Great solution. I just changed MIN_CLICK_INTERVAL=1000;
    – Nizam
    Apr 2, 2015 at 12:52
  • 8
    If I was to accurately button every 0.5 seconds, none of my subsequent clicks would get through because mLastClickTime would be updated each click. My suggestion would be to assign mLastClickTime after you check the interval.
    – k2col
    Jan 15, 2016 at 20:15
  • 1
    mLastClickTime=currentClickTime; should placed after if(elapsedTime<=MIN_CLICK_INTERVAL) return;
    – Loyea
    Jan 28, 2016 at 9:13
45

You can do it in very fancy way with Kotlin Extension Functions and RxBinding

   fun View.clickWithThrottle(throttleTime: Long = 600L, action: () -> Unit): Disposable =
        RxView.clicks(this)
                .throttleFirst(throttleTime, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { action() }

or

fun View.clickWithThrottle(throttleTime: Long = 600L, action: () -> Unit) {
    this.setOnClickListener(object : View.OnClickListener {
        private var lastClickTime: Long = 0

        override fun onClick(v: View) {
            if (SystemClock.elapsedRealtime() - lastClickTime < throttleTime) return
            else action()

            lastClickTime = SystemClock.elapsedRealtime()
        }
    })
}

and then just:

View.clickWithThrottle{ Your code }
3
  • over engenering Oct 9, 2018 at 19:38
  • 5
    Debounce for Rx won't work here well. Instead "ThrottleFirst" should fit better. demo.nimius.net/debounce_throttle here is example on how they differ. PS: and actually your clickWithDebounce implementation is throttle implementation, not debounce May 21, 2019 at 6:57
  • Is it possbile to use this method in DataBinding?
    – Cyrus
    Dec 4, 2020 at 13:25
44

Disabling the button or setting unclickable is not enough if you are doing computationally intensive work in onClick() since click events can get queued up before the button can be disabled. I wrote an abstract base class that implements OnClickListener that you can override instead, that fixes this problem by ignoring any queued up clicks:

/** 
 * This class allows a single click and prevents multiple clicks on
 * the same button in rapid succession. Setting unclickable is not enough
 * because click events may still be queued up.
 * 
 * Override onOneClick() to handle single clicks. Call reset() when you want to
 * accept another click.
 */
public abstract class OnOneOffClickListener implements OnClickListener {
    private boolean clickable = true;

    /**
     * Override onOneClick() instead.
     */
    @Override
    public final void onClick(View v) {
        if (clickable) {
            clickable = false;
            onOneClick(v);
            //reset(); // uncomment this line to reset automatically
        }
    }

    /**
     * Override this function to handle clicks.
     * reset() must be called after each click for this function to be called
     * again.
     * @param v
     */
    public abstract void onOneClick(View v);

    /**
     * Allows another click.
     */
    public void reset() {
        clickable = true;
    }
}

Usage is same as OnClickListener but override OnOneClick() instead:

OnOneOffClickListener clickListener = new OnOneOffClickListener() {
    @Override
    public void onOneClick(View v) {

        // Do stuff

        this.reset(); // or you can reset somewhere else with clickListener.reset();
    }
};
myButton.setOnClickListener(clickListener);
6
  • Thanks for the code. Based on what you've written here I've made similar class that prevents clicks if button or it's parent is hidden - it's funny that Android will queue clicks even if you hide button immediately after click.
    – nikib3ro
    Jul 29, 2012 at 9:33
  • 1
    I have a similar solution - you can just use this class in xml and it will wrap the clickListeners for you github.com/doridori/AndroidUtilDump/blob/master/android/src/…
    – Dori
    Sep 26, 2012 at 11:42
  • 4
    This is a good solution, but onClick() and reset() need to be synchronized, otherwise a double-click can still sneak in. Nov 5, 2013 at 8:52
  • 7
    @TomanMoney, how? Don't all click events happen on a single UI thread?
    – Ken
    Mar 17, 2015 at 20:46
  • @Dori the link is dead Sep 8, 2018 at 16:11
34

The KLEANEST Kotlin idiomatic way:

class OnSingleClickListener(private val block: () -> Unit) : View.OnClickListener {

    private var lastClickTime = 0L

    override fun onClick(view: View) {
        if (SystemClock.elapsedRealtime() - lastClickTime < 1000) {
            return
        }
        lastClickTime = SystemClock.elapsedRealtime()

        block()
    }
}

fun View.setOnSingleClickListener(block: () -> Unit) {
    setOnClickListener(OnSingleClickListener(block))
}

Usage:

button.setOnSingleClickListener { ... }

Or with an added parameter for controlling the throttle

class OnClickListenerThrottled(private val block: () -> Unit, private val wait: Long) : View.OnClickListener {

    private var lastClickTime = 0L

    override fun onClick(view: View) {
        if (SystemClock.elapsedRealtime() - lastClickTime < wait) {
            return
        }
        lastClickTime = SystemClock.elapsedRealtime()

        block()
    }
}

/**
 * A throttled click listener that only invokes [block] at most once per every [wait] milliseconds.
 */
fun View.setOnClickListenerThrottled(wait: Long = 1000L, block: () -> Unit) {
    setOnClickListener(OnClickListenerThrottled(block, wait))
}

Usages:

button.setOnClickListenerThrottled(2000L) { /** some action */}
or
button.setOnClickListenerThrottled { /** some action */}
1
  • This way click animation could be played several times while click really will be triggered really once. The "disable" method is more convinient to prevent several click animations to play.
    – Stan
    Sep 19, 2022 at 12:20
18

I also ran into a similar problem, I was displaying some date pickers & time pickers where sometimes it got clicked 2 times. I have solved it with this:

long TIME = 1 * 1000;
@Override
public void onClick(final View v) {
v.setEnabled(false);
    
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            v.setEnabled(true);
        }
    }, TIME);
}

You can change time depending upon your requirement.

1
  • This is the real solution, since it reactivates the button automatically after the time has elapsed. The other solutions block the button permanently if you click twice quickly. This solution fixes the problem! Thanks
    – Nes
    May 9, 2020 at 10:03
17

I know it's an old question, but I share the best solution I found to solve this common problem

        btnSomeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Prevent Two Click
            Utils.preventTwoClick(view);
            // Do magic
        }
    });

And in another file,like Utils.java

    /**
 * Método para prevenir doble click en un elemento
 * @param view
 */
public static void preventTwoClick(final View view){
    view.setEnabled(false);
    view.postDelayed(
        ()-> view.setEnabled(true),
        500
    );
}
9

setEnabled(false) works perfectly for me.

The idea is I write { setEnabled(true); } in the beginning and just make it false on the first click of the button.

8

The actual solution to this problem is to use setEnabled(false) which greys out the button, and setClickable(false) which makes it so the second click can not be received I have tested this and it seem to be very effective.

8

If someone is still looking for a short answer you can use the below code

 private static long mLastClickTime = 0;
  if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) { // 1000 = 1second
         return;
    }
 mLastClickTime = SystemClock.elapsedRealtime();

This code will go inside the if statement whenever the user clicks on the View within 1 second and then the return; will be initiated and the further code will not initiate.

1
  • 3
    This should be the accepted answer. Super simple and it works even if you click very fast ! Thanks for this. Nov 12, 2019 at 20:25
8

My solution is try to using a boolean variable :

public class Blocker {
    private static final int DEFAULT_BLOCK_TIME = 1000;
    private boolean mIsBlockClick;

    /**
     * Block any event occurs in 1000 millisecond to prevent spam action
     * @return false if not in block state, otherwise return true.
     */
    public boolean block(int blockInMillis) {
        if (!mIsBlockClick) {
            mIsBlockClick = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mIsBlockClick = false;
                }
            }, blockInMillis);
            return false;
        }
        return true;
    }

    public boolean block() {
        return block(DEFAULT_BLOCK_TIME);
    }
}

And using as below:

view.setOnClickListener(new View.OnClickListener() {
            private Blocker mBlocker = new Blocker();

            @Override
            public void onClick(View v) {
                if (!mBlocker.block(block-Time-In-Millis)) {
                    // do your action   
                }
            }
        });

UPDATE: Kotlin solution, using view extension

fun View.safeClick(listener: View.OnClickListener, blockInMillis: Long = 500) {
    var lastClickTime: Long = 0
    this.setOnClickListener {
        if (SystemClock.elapsedRealtime() - lastClickTime < blockInMillis) return@setOnClickListener
        lastClickTime = SystemClock.elapsedRealtime()
        listener.onClick(this)
    }
}
1
  • Perfect. The Kotlin extension worked like a charm. Thanks.
    – groff07
    Jan 30, 2023 at 18:40
6

Below code will prevent user to click multiple times within a fractions of seconds and allow only after 3 seconds.

private long lastClickTime = 0;

View.OnClickListener buttonHandler = new View.OnClickListener() {
    public void onClick(View v) {
        // preventing double, using threshold of 3000 ms
        if (SystemClock.elapsedRealtime() - lastClickTime < 3000){
            return;
        }

        lastClickTime = SystemClock.elapsedRealtime();
    }
}
1
  • This is the only answer that has worked for me. 3000ms is fine for me. 1000ms was not enough in my case. Feb 4, 2021 at 18:29
6

In kotlin

button.setOnClickListener { 
    it?.apply { isEnabled = false; postDelayed({ isEnabled = true }, 400) } //400 ms
    //do your work
}
6

We could use the button just synchronized like:

Example #1 (Java)

@Override
public void onClick(final View view) {
    synchronized (view) {

        view.setEnabled(false);

        switch (view.getId()) {
            case R.id.id1:
                ...
                break;
            case R.id.id2:
                ...
                break;
                ...
        }

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                view.setEnabled(true);
            }
        }, 1000);
    }
}

Example #2 (kotlin) using synchronized

myButton.setOnClickListener { view ->
            synchronized(view) {
                view.isEnabled = false

                // do something

                view.postDelayed({ view.isEnabled = true }, 500L)
            }
        }

Good Luck)

1
5

Click Guard works well with Butter Knife

ClickGuard.guard(mPlayButton);
5
  • 4
    separete linrary for handle double click on button? ha Oct 9, 2018 at 19:39
  • Can I use this inside custom button ? Dec 25, 2019 at 7:14
  • @AraBadalyan what do you mean by 'inside'. Just pass your custom button as param for guard method. Then your button will be protect from double click Dec 25, 2019 at 8:14
  • I mean I don't want to add ClickGuard.guard(mPlayButton) in all activities that use onclick. I want to create CustomButton extent Button and put ClickGuard inside CustomButton. But when I add ClickGuard in CustomButton constructor it didn't work. Dec 27, 2019 at 5:39
  • @AraBadalyan that's right. It doesn't work that way. Dec 27, 2019 at 9:30
5

in my situation i was using a button view and it was taking the clicks too quickly. just disable the clickable and enable it again after a few seconds...

Basically i made a wrapper class that wraps around your Views onClickListener. you can also set a custom delay if you want.

public class OnClickRateLimitedDecoratedListener implements View.OnClickListener {

    private final static int CLICK_DELAY_DEFAULT = 300;
    private View.OnClickListener onClickListener;
    private int mClickDelay;


        public OnClickRateLimitedDecoratedListener(View.OnClickListener onClickListener) {
            this(onClickListener, CLICK_DELAY_DEFAULT);
        }

        //customize your own delay
        public OnClickRateLimitedDecoratedListener(View.OnClickListener onClickListener, int delay) {
            this.onClickListener = onClickListener;
            mClickDelay = delay;
        }

        @Override
        public void onClick(final View v) {
            v.setClickable(false);
            onClickListener.onClick(v);

            v.postDelayed(new Runnable() {
                @Override
                public void run() {
                    v.setClickable(true);
                }
            }, mClickDelay);
        }
    }

and to call it simply do this:

mMyButton.setOnClickListener(new OnClickRateLimitedDecoratedListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 doSomething();
             }
         }));

or provide your own delay:

 mMyButton.setOnClickListener(new OnClickRateLimitedDecoratedListener(new View.OnClickListener() {
                     @Override
                     public void onClick(View v) {
                         doSomething();
                     }
                 },1000));

UPDATE: Above ways a little old fashion now that RxJava is so prevalent. as others have mentioned, in android we could use a throttle to slow down the clicks. here is one example:

 RxView.clicks(myButton)
                    .throttleFirst(2000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                    .subscribe {
                        Log.d("i got delayed clicked")
                    }
        }

you can use this library for it: implementation 'com.jakewharton.rxbinding2:rxbinding:2.0.0'

5

Kotlin create class SafeClickListener

class SafeClickListener(
        private var defaultInterval: Int = 1000,
        private val onSafeCLick: (View) -> Unit
) : View.OnClickListener {
    private var lastTimeClicked: Long = 0    override fun onClick(v: View) {
        if (SystemClock.elapsedRealtime() - lastTimeClicked < defaultInterval) {
            return
        }
        lastTimeClicked = SystemClock.elapsedRealtime()
        onSafeCLick(v)
    }
}

create a function in baseClass or else

fun View.setSafeOnClickListener(onSafeClick: (View) -> Unit) {val safeClickListener = SafeClickListener {
        onSafeClick(it)
    }
    setOnClickListener(safeClickListener)
}

and use on button click

btnSubmit.setSafeOnClickListener {
    showSettingsScreen()
}
2
  • 3
    The cleanest solution with extensions! Thanks! Oct 25, 2019 at 8:07
  • 1
    Perfect answer thank you Oct 12, 2021 at 11:03
5

My solution (Kotlin):

class OnDebouncedClickListener(private val delayInMilliSeconds: Long, val action: () -> Unit) : View.OnClickListener {
    var enable = true

    override fun onClick(view: View?) {
        if (enable) {
            enable = false
            view?.postDelayed(delayInMilliSeconds) { enable = true }
            action()
        }
    }
}

fun View.setOnDebouncedClickListener(delayInMilliSeconds: Long = 500, action: () -> Unit) {
    val onDebouncedClickListener = OnDebouncedClickListener(delayInMilliSeconds, action)
    setOnClickListener(onDebouncedClickListener)
}

Use :

button.apply {       
            setOnDebouncedClickListener {
                //your action on click
            }
        }
5

With Kotlin extension function :

fun View.onSingleClick(action: (v: View) -> Unit) {
    setOnClickListener(object : View.OnClickListener {
        override fun onClick(v: View) {
            isClickable = false
            action(v)
            postDelayed({ isClickable = true }, 700)
        }
    })
}

usage:

button.onSingleClick { myAction() }
5

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);
}
4
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            //to prevent double click
            button.setOnClickListener(null);
        }
    });
0
4

I found none of these suggestions works if the onClick method doesn't return immediately. The touch event is queued by Android and the next onClick is called only after the first one is finished. (Since this is done on the one UI thread this is really normal.) I needed to use the time when the the onClick function is finished + one boolean variable to mark whether the given onClick is running. Both these marker attributes are static to avoid any onClickListener to run at the same time. (If user clicks on another button) You can simple replace your OnClickListener to this class and instead of implementing the onClick method you need to implement the abstract oneClick() method.

    abstract public class OneClickListener implements OnClickListener {

    private static boolean started = false;
    private static long lastClickEndTime = 0;

    /* (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    final public void onClick(final View v) {
        if(started || SystemClock.elapsedRealtime()-lastClickEndTime <1000 ){
            Log.d(OneClickListener.class.toString(), "Rejected double click, " + new Date().toString() );
            return; 
        }
        Log.d(OneClickListener.class.toString(), "One click, start: " + new Date().toString() );
        try{
            started = true;
            oneClick(v);
        }finally{
            started = false;
            lastClickEndTime = SystemClock.elapsedRealtime();
            Log.d(OneClickListener.class.toString(), "One click, end: " + new Date().toString() );
        }
    }

    abstract protected void oneClick(View v);
}
4

Kotlin extension that allows for concise inline code & variable double click wait times

fun View.setDoubleClickListener(listener: View.OnClickListener, waitMillis : Long = 1000) {
    var lastClickTime = 0L
    setOnClickListener { view ->
        if (System.currentTimeMillis() > lastClickTime + waitMillis) {
            listener.onClick(view)
            lastClickTime = System.currentTimeMillis()
        }
    }
}

Usage:

anyView.setNoDoubleClickListener(View.OnClickListener { v ->
    // do stuff
})

Or

anyView.setNoDoubleClickListener(View.OnClickListener { v ->
    // do stuff
}, 1500)
2
  • Awesome, everyone should use this, its absolutely nice piece of code and great reason why everyone should migrate to kotlin. Jan 14, 2019 at 6:58
  • Could be nicer if the waitMillis is just hardcoded, then the outer parentheses can be eliminated.
    – WindRider
    Sep 16, 2019 at 15:15
3

It seems that setting your click listeners in onResume and nulling them out in onPause does the trick too.

0
3

For me only remembering timestamp and checking against it (that more than 1 sec passed since previous click) helped.

3

I hope this can help YOU, put the code in you event handler.

// --------------------------------------------------------------------------------

    boolean hasTag = null != which.getTag( R.id.preventing_double_click_tag );

    if ( hasTag ) {
        // Do not handle again...
        return;
    } else {
        which.setTag( R.id.action, Boolean.TRUE );

        which.postDelayed( new Runnable() {
            @Override
            public void run() {
                which.setTag( R.id.action, null );
                Log.d( "onActin", " The preventing double click tag was removed." );
            }

        }, 2000 );
    }
3

you can also use rx bindings by jake wharton to accomplish this. here is a sample that pads 2 seconds between successive clicks:

RxView.clicks(btnSave)
                .throttleFirst(2000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept( Object v) throws Exception {
//handle onclick event here
                });

//note: ignore the Object v in this case and i think always.

0
3

Adding to Jim's answer the code can be made more concise:

fun View.setOnSingleClick(onClick: () -> Unit) {
    var lastClickTime = 0L
    setOnClickListener {
        if (currentTimeMillis() > lastClickTime + 750) onClick()
        lastClickTime = currentTimeMillis()
    } 
}

Usage:

aView.setOnSingleClick {  }
3

Below is the kotlin way with extension function that will work for all views, keep below function in ur Utils or any File

fun View.preventDoubleClick() {
this.isEnabled = false
this.postDelayed( { this.isEnabled = true }, 1000)
}

Below is how to use it from fragment or activity

anyIdOfView?.setOnClickListener {
it.preventDoubleClick()
YourAction()
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.