问题是:如何在倒计时期间从CountDownTimer添加或删除时间?
例如:用户做了一件好事:+ 5秒,用户做错了什么:-5秒。
有人可以帮我一些代码吗?
答案 0 :(得分:5)
也许是这样的
abstract class MyTimer {
public MyTimer(long deadline, long interval)
{
mDeadline = deadline;
mInterval = interval;
mTimer = new MyCountDownTimer(mDeadline, mInterval);
}
public synchronized void start() {
mTimer.start();
}
public abstract void onTick(long time);
public abstract void onFinish();
public synchronized void userDidRight()
{
mTimer.cancel();
mTimer = new MyCountDownTimer(mDeadline, mInterval += 5000);
mTimer.start();
}
public synchronized void userDidWrong()
{
mTimer.cancel();
mTimer = new MyCountDownTimer(mDeadline, mInterfval -= 5000);
mTimer.start();
}
private class MyCountDownTimer extends CountDownTimer() {
private abstract void onFinish() {
MyTimer.this.onFinish();
}
private abstract void onTick(long time) {
MyTimer.this.onTick(time);
}
}
private MyCountDownTimer mTimer;
}
答案 1 :(得分:1)
每次用户更改时都可以重新启动计时器:
class Timer {
private long remainingTime;
private CoundDownTimer timer;
public void addTime(long addedTimeInMillis) {
createNewTimer(remainingTime + addedTimeInMills);
}
public void createNewTimer(long timeInMillis) {
if(timer != null) {
timer.cancel();
}
timer = new CountDownTimer(timeInMillis, 1000) {
@Override
public void onTick(final long millisUntilFinished) {
remainingTime = millisUntilFinished;
}
@Override
public void onFinish() {
// do something here
}
}.start();
}
}
答案 2 :(得分:1)
private class startTimer extends CountDownTimer
{
public startTimer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
currenttime=millisUntilFinished;
textview.setText("" + currenttime / 1000);
}
@Override
public void onFinish() {
textview.setText("done");
}
}
上面的类是CountDownTimer的简单派生类
CountDownTimer timer = new CountDownTimer(30000,1000);
timer.start();
long currentTime;
例如,上述计时器从30秒开始,每秒减少一个。 要动态增加或减少计时器,您可以取消旧计时器并使用新时间进行初始化,如下所示
timer.cancel();
timer = new CountDownTimer(currentTime+5000,1000);// +5000 to increase by 5 secs
timer.start();
您可以将计时器,currentTime变量设为全局,然后您可以在不同位置使用代码的两个不同部分。