Time between two button clicks

2019-06-07 07:30发布

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.

2条回答
再贱就再见
2楼-- · 2019-06-07 07:42

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;
查看更多
神经病院院长
3楼-- · 2019-06-07 08:04

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();
    }
}  
查看更多
登录 后发表回答