I'm trying to do something pretty simple, but for some reason I can't get it to work. I have two circular buttons.
-When I simply click the top (green) button, I want the buttons to switch colors and remain that way.
-If I HOLD a button for 2 seconds, I want the colors to swap for as long as I hold the button, but then revert back to their original colors as soon as I let go.
I am trying to use an OnClickListener. I am using a switch with 2 cases: MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP. (see code below)
To get the duration the button is being held, I use System.currentTimeMillis() within a while loop (while button is being held) --> (if timeElapsed > 2000){switch the colors}
full code below:
greenbutton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
startTime = System.currentTimeMillis();
while (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
currentTime = System.currentTimeMillis();
elapsedTime = currentTime - startTime;
if (elapsedTime > 500) {
if (switched) {
revertButtons();
return true;
} else {
switchButtons();
return true;
}
}
}
case MotionEvent.ACTION_UP:
if (switched) {
revertButtons();
elapsedTime = 0;
currentTime = 0;
startTime = 0;
return true;
} else {
switchButtons();
elapsedTime = 0;
currentTime = 0;
startTime = 0;
return true;
}
}
return false;
}
});
Try use the predefined methods -
onClickListener( () => {} )
for single clicks
onLongClickListener( () => {} )
for long clicks
This way you don't need to calculate the time the user clicked and by running a loop or thread you may keep changing colours on long clicks.
UPDATED
As mentioned in comment its needed only a particular timing use the following algorithm-
** UPDATED**
As the time of click is required follow :