How to set delay in Android onClick function

Instead of sleeping in the onclick, you could post a delayed message to a handler (with associated runnable) and have it update the UI. Obviously fit this into the design of your app and make it work, but the basic idea is this:

//Here's a runnable/handler combo
private Runnable mMyRunnable = new Runnable()
{
    @Override
    public void run()
    {
       //Change state here
    }
 };

Then from onClick you post a delayed message to a handler, specifying that runnable to be executed.

Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 1000);//Message will be delivered in 1 second.

Depending on how complicated your game is, this might not be exactly what you want, but it should give you a start.

Leave a Comment