I have a button, I press it and continue to holding it, if holding time exceeds certain time interval it fires some kind of intent, how can i do this. Thanks
long lastDown;
long keyPressedDuration ;
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
lastDown = System.currentTimeMillis();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
keyPressedDuration = System.currentTimeMillis() - lastDown;
}
}
};
try this
You can use Touch Listener
to do this.
Try:
Handler handler = new Handler();
b.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.postDelayed(run, 5000/* OR the amount of time you want */);
break;
default:
handler.removeCallbacks(run);
break;
}
return true;
}
});
Where b
is the view
(in your case it should button) on which you want to make long click.
And Runnable
run
is as follows
Runnable run = new Runnable() {
@Override
public void run() {
// Your code to run on long click
}
};
Hope it will help... :)
Detect [ACTION_DOWN][1]
and [ACTION_UP][2]
events.
When button is pressed ([ACTION_DOWN][1]
), start timer, measure time... If timer exceeds, invoke Intent. When button is released ([ACTION_UP][2]
) stop timer.
final Timer timer = new Timer();
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch ( arg1.getAction() ) {
case MotionEvent.ACTION_DOWN:
//start timer
timer.schedule(new TimerTask() {
@Override
public void run() {
// invoke intent
}
}, 5000); //time out 5s
return true;
case MotionEvent.ACTION_UP:
//stop timer
timer.cancel();
return true;
}
return false;
}
});
When button will be pressed, timer will be started. If button will be released before 5 seconds timeout, nothing will happen, otherwise your desired action will be executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With