Use an onTouchListener on your button to capture when it is touched and then handle the motion even accordingly. Below is an example but you can read more about handling touch events at the link provided
Button button = (Button) findViewById(R.id.my_button);
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
//start timer here
break;
case MotionEvent.ACTION_UP:
//stop timer
break;
}
}
});
Starting the timer is more complicated. There are a number of ways to do this. This post has some good ideas. If you have a limited number of actions you need to trigger, I would consider using a Handler
and creating a Runnable
for each series of events. If the first action you want to happen occurs after 5 seconds, use the postDelayed method for Handler
to call the appropriate Runnable
after that amount of time. By chaining calls to handler.postDelayed() you can start different actions the longer the button is held. To cancel the action on ACTION_UP simply removeCallbacks on your handler for that Runnable
. The sample code is in the link I attached.
The other methods, which are interesting but that I have never used, involve looking at the time the touch occurred and then subtracting the start time from system time to get the length of the action. Interesting concept, however, you would need to modify the code slightly to make it work since, in my experience, holding a finger on the screen continuously generates touch events which would make calculating duration useless.
private MotionEvent touch == null;
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction == MotionEvent.ACTION_DOWN){
if(touch == null)
touch = event;
long duration = android.os.SystemClock.elapsedRealtime()
- touch.getDownTime();
if(duration == THRESHOLD){
//do something
}
}
}
I have not tested that code but you can see the idea. By checking the duration of the initial down touch you could fire off different actions over time.