user896692
user896692

Reputation: 2371

Time between two button clicks

I´ve two buttons and I want to count the time between two clicks. I know how to do that once:

 Long starttime = System.currentTimeMillis();
 Long endtime = System.currentTimeMillis();
 Long differenz = ((endtime-starttime) / 1000);

Now, I want on the second click, that the count starts from zero again until the first button is clicked. Then, measure the time between first and second button click and so on.

Maybe it´s a really simple thing but I don´t know how to do...

EDIT: Ok, I try to make it clear:

I have Button A and B. I want the user to alternately push button A and B. When the user clicks on Button A, I want a timer to measure the time until B is clicked. Until here, everything is clear to me. Now I want that the time between the click on B till the click to A is measured, always alternated between A and B.

I don´t know what to do after the click on B that the time is measured again until A.

Upvotes: 1

Views: 4770

Answers (2)

Hoan Nguyen
Hoan Nguyen

Reputation: 18151

Class members

boolean mButtonAClicked;
boolean mButtonBClicked;

long mStartTime = 0;

When Button A is clicked

if (mButtonAClicked)
{
    // button A is clicked again, stop application
}
else
{
    mButtonAClicked = true;
    mButtonBClicked = false;
    if (mStartTime != 0) // Button B was clicked
    {
         Long endtime = System.currentTimeMillis();
         Long differenz = ((endtime-starttime) / 1000);
         mStartTime = System.currentTimeMillis();
    }
}  

When Button B is cliked

if (mButtonBClicked)
{
    // button B is clicked again, stop application
}
else
{
    mButtonBClicked = true;
    mButtonAClicked = false;
    if (mStartTime != 0) // Button A was clicked
    {
         Long endtime = System.currentTimeMillis();
         Long differenz = ((endtime-starttime) / 1000);
         mStartTime = System.currentTimeMillis();
    }
}  

Upvotes: 2

Jean Waghetti
Jean Waghetti

Reputation: 4727

Create a field to hold last time each was pressed.

long aMillisPressed;
long bMillisPressed;

When Button A is clicked:

aMillisPressed = System.currentTimeMillis();
long timeElapsedSinceBPressed = aMillisPressed - bMillisPressed;

And when B is clicked:

bMillisPressed = System.currentTimeMillis();
long timeElapsedSinceAPressed = bMillisPressed - aMillisPressed;

Upvotes: 1

Related Questions