Carlos Pereira
Carlos Pereira

Reputation: 1924

OnTouch delay (Android)

I have an app where I need to have a delay after each touch in an ImageButton.

I tried the Thread.sleep() method, but I am not sure if this is the best way to deal with it.

What do you guys recommend?

Any help is appreciatted!

ONE MORE THING: I want the content of the onTouch() event to be fired THEN I want to delay "X" seconds the next onTouch() event. It's like to prevent the user to click too many times in the button.

Upvotes: 0

Views: 4359

Answers (1)

Pavel Dudka
Pavel Dudka

Reputation: 20934

Since all touch events are handled by UI thread, Thread.sleep() will block your UI thread which is (I hope) not what you are looking for. I think the most correct way to solve your problem would be using postDelayed(Runnable, long) interface in your onClick handler which allows your to delay execution:

@Override
public void onClick(View v)
{
    postDelayed(new Runnable()
    {

        @Override
        public void run()
        {
            // do your stuff here
        }
    }, 10000); //10sec delay
}

UPDATE:

If you want user to prevent clicking too fast on your image view, I strongly recommend go with onClick rather than onTouch (unless there are serious reasons for that)

However, please see the code snippet which might help you:

private boolean blocked = false;
private Handler handler = new Handler();

@Override
public boolean onTouchEvent(MotionEvent event)
{
    if (event.getAction() == MotionEvent.ACTION_DOWN)
    {
        if (!blocked)
        {
            blocked = true;
            handler.postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    blocked = false;
                }
            }, 1000);
        } else
        {
            return false;
        }
    }
    return super.onTouchEvent(event);
}

Upvotes: 4

Related Questions