I would like to to have a button that executes a method repeatedly when it is pressed. Once it is released it should stop executing the method.
Example: A user presses and holds down the button for 5 seconds. Then the method shall be executed over and over again during those 5 seconds. In addition, the method that gets called repeatedly needs to know for how long the button is pressed so far.
Here is what I have so far. I am using an onTouchListener
:
myButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
myButton.setText("Pressed!");
while(myButton.isPressed()) {
doSomething(event);
}
break;
case MotionEvent.ACTION_UP:
myButton.setText("Press me!");
}
return false;
};
private void doSomething(MotionEvent event) {
// Do some calculation with the time the button is pressed so far
}
});
My problem is that the while-loop
is not working as it should and that I dont know how to get the time the button was pressed. Maybe with the event?? Any ideas?