我在我的项目中实现了countup概念..它包含3个问题按钮..如果用户点击第一个按钮计数就开始了。每当他按下第二个问题时,计数应该重置。如果用户返回第一个按钮,那么倒计时应更新它暂停的位置..
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long systemTime = System.currentTimeMillis();
Log.d("System Time", String.valueOf(systemTime));
long millis = systemTime - startTime;
Log.d("millis", String.valueOf(millis));
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
qstimer.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
答案 0 :(得分:0)
向按钮添加OnCLickListener:
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v)
{
if (mOnButtonClickListener != null)
{
switch (v.getId())
{
case R.id.on:
startTime = SystemClock.elapsedRealtime();
timerHandler.post(timerRunnable);
break;
case R.id.off:
timerHandler.removeCallbacks(timerRunnable);
break;
}
}
}
};
如果您希望关闭按钮以暂停计时器,则必须存储暂停开始时间和总暂停时间:
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v)
{
if (mOnButtonClickListener != null)
{
switch (v.getId())
{
case R.id.on:
if(paused)
{
pausedTime += SystemClock.elapsedRealtime()-pauseStartTime;
}
else
{
startTime = SystemClock.elapsedRealtime();
}
timerHandler.post(timerRunnable);
break;
case R.id.off:
pauseStartTime = SystemClock.elapsedRealtime();
timerHandler.removeCallbacks(timerRunnable);
break;
}
}
}
};
在你的runnable中:
long millis = time - startTime - pausedTime;
希望有所帮助
答案 1 :(得分:0)
试试这个
在第一个按钮(ON)中粘贴此代码,在第二个按钮(OFF)中粘贴相同的代码但不是" i == 0"拿另一个变量
if(i == 0){
pauseTime = timeSwap+= timeInMillies;
timeMap.put(keyQuestion, pauseTime);
keyQuestion = q1.getText().toString();
timerStart();
i = 1;
}
else if(i == 1){
myHandler.removeCallbacks(updateTimerMethod);
pauseTime = timeSwap+= timeInMillies;
timeMap.put(keyQuestion, pauseTime);
keyQuestion = q1.getText().toString();
timeSwap = 0L;
timeSwap += timeMap.get(keyQuestion);
startTime = SystemClock.uptimeMillis();
myHandler.postDelayed(updateTimerMethod, 0);
}
希望它有所帮助。