Reputation: 5
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;
}
});
Upvotes: 0
Views: 795
Reputation: 1348
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 :
Upvotes: 1
Reputation: 1482
I found a simple solution studying how the long press event works.
Each time a view is clicked, a Runnable
of type CheckForLongPress
is added to a queue with a delay. If the delay ends, the OnLongClickListener
is called. If there is a different event before the delay ends, then, the CheckForLongPress Runnable
is removed from de queue.
I just override the public method postDelayed(Runnable action, long delayMillis)
of the view to change the OS delay
@Override public boolean postDelayed(Runnable action, long delayMillis) {
boolean isLongPress = action.getClass().getSimpleName().equals("CheckForLongPress");
return super.postDelayed(action, isLongPress ? LONG_PRESS_MILLIS : delayMillis);
}
I set LONG_PRESS_MILLIS
to 100 and it's working!
Hope it helps!!! ;)
Credit: MArtinCR
Upvotes: 0