Reputation: 3106
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
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
Reputation: 210
Thats what the LongClickListener is for: http://developer.android.com/reference/android/view/View.OnLongClickListener.html
Upvotes: 3
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
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