ArcDare
ArcDare

Reputation: 3106

ANDROID: Creating a button that needs to be pushed for X seconds

What I am looking for is to have a button where:

If you just push it, does nothing.

If you push and hold it for, let's say, 3 seconds, perform an action().

Any idea of what to do?

Thank you in advance.

Upvotes: 0

Views: 138

Answers (4)

Jave
Jave

Reputation: 31846

If you want to be able to specify the time, here is an implementation of OnTouchListener that does that for you, without using a Timer:

class TimedTouchListener implements OnTouchListener{
    private final long millisRequired = 3000;
    private long downTime;

    @Override
    public boolean onTouch(View v, MotionEvent event){
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN:
            downTime = System.currentTimeMillis();
            return true;
            break;
        case MotionEvent.ACTION_UP:
            long upTime = System.currentTimeMillis();
            if( upTime - downTime > millisRequired ){
                doAction(); //doAction can be a method call, or any code you want to be executed.
                return true;
            }else{
                return true;
            }
        }
        return false;
    }
}

If you don't need to specify the time, just go with an OnLongClickListener as suggested by others.

Upvotes: 5

andy droid
andy droid

Reputation: 210

Thats what the LongClickListener is for: http://developer.android.com/reference/android/view/View.OnLongClickListener.html

Upvotes: 3

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43098

button.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        // remeber here that ACTION_DOWN has occured
        // set the timer for 3 seconds
        // if ACTION_UP occured and timer has elapsed, then call action().
    }});

or as ntc noticed, you can use OnLongClickListener instead.

Upvotes: 4

smitec
smitec

Reputation: 3049

on finger down start a 3 second timer. on finger up if timer is still active cancel it. on timer expire run action.

Upvotes: 0

Related Questions