beeblebrox
beeblebrox

Reputation: 13

Android canceling timeout function after time has started

I want the button to be visible for 5 seconds after I click an image, however if I click the image again within those 5 seconds I don't want the button to be hidden when the first 5 seconds are up, but when the second 5 seconds are. So basically I want to cancel the function after the timeout has started. Is such a thing possible? Is there any other way to achieve the same effect?

This is the timeout method function that I am using.

@Override
public boolean onTouch(View v, MotionEvent event) {

    btnRemove.setVisibility(View.VISIBLE);

    final Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            btnRemove.setVisibility(View.GONE);
        }
    }, 5000);
}

Upvotes: 1

Views: 191

Answers (1)

Mark
Mark

Reputation: 9919

Make sure Handler is a instance variable, rather than a local variable, which currently falls out of scope when the onTouch method returns.

private final Handler handler = new Handler(Looper.getMainLooper()); // instance variable

 
@Override
public boolean onTouch(View v, MotionEvent event) {

    btnRemove.setVisibility(View.VISIBLE);

    handler.removeCallbacksAndMessages(null); // remove previous Runnable - optional
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            btnRemove.setVisibility(View.GONE);
        }
    }, 5000);
}

At any point in the enclosing class you can then call : handler.removeCallbacksAndMessages(null); which will remove any delayed/queued Runnable objects.

Upvotes: 2

Related Questions