Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a runnable from a handler object added by postDelayed?

I have an "open" animation and am using Handler.postDelayed(Runnable, delay) to trigger a "close" animation after a short delay. However, during the time between open and close, there is possibly another animation triggered by a click.

My question is, how would I cancel the "close" animation in the handler?

like image 250
Bruce Lee Avatar asked Sep 02 '10 12:09

Bruce Lee


People also ask

How do I remove runnable from Handler?

Just use the removeCallbacks(Runnable r) method.

How do I cancel my postDelayed handler?

removecallback and handler = null; to cancel out the handle just to keep the code clean and make sure everything will be removed.

What is new handler () postDelayed?

postDelayed(Runnable r, Object token, long delayMillis) Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. final void. removeCallbacks(Runnable r) Remove any pending posts of Runnable r that are in the message queue.


2 Answers

Just use the removeCallbacks(Runnable r) method.

like image 196
Cristian Avatar answered Sep 21 '22 05:09

Cristian


Cristian's answer is correct, but as opposed to what is stated in the answer's comments, you actually can remove callbacks for anonymous Runnables by calling removeCallbacksAndMessages(null);

As stated here:

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

like image 44
Daniel L. Avatar answered Sep 20 '22 05:09

Daniel L.